Search code examples
c#wpfxamlbindingdatacontext

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>

Solution

  • 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;