DataContext System.NullReferenceException c# xaml

DataContext System.NullReferenceException c# xaml

我试图实现一个来自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 的构造函数中引用 MyTextBox,则需要在调用 InitializeComponent() 之后执行此操作,这会构建 [=] 的树16=]

InitializeComponent();

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