2015-08-23 2 views
1

Я пытался реализовать пример из Msdn, но пустая ссылка исключение ocurred, и я не знаю, почему: Так вот мой C# код файла MainPage.xaml.cs:DataContext System.NullReferenceException C# XAML

 // 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> 
+0

Где вы его зовете? Возможно ли это в конструкторе 'Window'? Если да, это до или после 'InitializeComponent'? – dkozl

+0

Можете ли вы дать контекст для кода? Разве это в конструкторе? Если да, вызываете ли вы InitializeComponent() перед этим? (это самая похищенная ловушка). –

+0

Вы правы, я назвал его после него, теперь я не получаю исключение, но на переднем плане не получается red @dkozl –

ответ

1

Как уже упоминалось в комментариях, если вы обратитесь к MyTextBox в consstructor в Window «S вы должны сделать это после того, как InitializeComponent() называется, который строит дерево XAML

InitializeComponent(); 

MyColors textcolor = new MyColors(); 
textcolor.Brush1 = new SolidColorBrush(Colors.Red); 
MyTextBox.DataContext = textcolor; 
Смежные вопросы