简体   繁体   中英

DataContext System.NullReferenceException c# xaml

I tried to implement an example from Msdn but a null reference exception ocurred and I don't know why: So here is my C# code of the Mainpage.xaml.cs file:

     // 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);

And here is the xaml code behind:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox x:Name="MyTextBox" Text="Text" Foreground="{Binding Brush1}"/>
</Grid>

As mentioned in the comment if you refer to MyTextBox in the Window 's consstructor you need to do it after InitializeComponent() is called which builds the tree of the XAML

InitializeComponent();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM