【发布时间】:2015-11-17 00:00:49
【问题描述】:
我试图从Msdn 中实现一个示例,但是发生了一个空引用异常,我不知道为什么: 所以这是我的 Mainpage.xaml.cs 文件的 C# 代码:
// Create an instance of the MyColors class
// that implements INotifyPropertyChanged.
MyColors textcolor = new MyColors();
// Brush1 is set to be a SolidColorBrush with the value Red.
textcolor.Brush1 = new SolidColorBrush(Colors.Red);
// Set the DataContext of the TextBox MyTextBox.
MyTextBox.DataContext = textcolor; //HERE THE ERROR OCCURS!
// Create the binding and associate it with the text box.
Binding binding = new Binding() { Path = new PropertyPath("Brush1") };
MyTextBox.SetBinding(TextBox.ForegroundProperty, binding);
这是后面的 xaml 代码:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBox x:Name="MyTextBox" Text="Text" Foreground="{Binding Brush1}"/>
</Grid>
【问题讨论】:
-
你在哪里称呼它?
Window的构造函数中是否有任何机会?如果是,是在InitializeComponent之前还是之后? -
你能给出代码的上下文吗?它是否在构造函数中被收集?如果是这样,你是在它之前调用 InitializeComponent() 吗? (这是最明显的陷阱)。
-
你说得对,我在它之后调用了它,现在我没有例外,但前景没有变红@dkozl
-
你能展示一下
MyColors的样子吗?主要是Brush1是公开的吗? -
@dkozl 我找到了我的答案......因为前景仅适用于文本块失去焦点的情况。如果您将我的问题作为答案回答:D 我可以将其标记为解决方案
标签: c# wpf xaml binding datacontext