DataContext System.NullReferenceException c#xaml

时间:2015-08-23 14:01:57

标签: c# wpf xaml binding datacontext

我尝试从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>

1 个答案:

答案 0 :(得分:1)

如评论中所述,如果您在MyTextBox的consstructor中引用Window,则需要在调用InitializeComponent()之后执行此操作,以构建XAML的树

InitializeComponent();

MyColors textcolor = new MyColors();
textcolor.Brush1 = new SolidColorBrush(Colors.Red);
MyTextBox.DataContext = textcolor;