【问题标题】:DataContext System.NullReferenceException c# xamlc# xaml DataContext System.NullReferenceException
【发布时间】:2015-11-17 00:00:49
【问题描述】:

我试图从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的构造函数中是否有任何机会?如果是,是在InitializeComponent 之前还是之后?
  • 你能给出代码的上下文吗?它是否在构造函数中被收集?如果是这样,你是在它之前调用 InitializeComponent() 吗? (这是最明显的陷阱)。
  • 你说得对,我在它之后调用了它,现在我没有例外,但前景没有变红@dkozl
  • 你能展示一下MyColors 的样子吗?主要是Brush1 是公开的吗?
  • @dkozl 我找到了我的答案......因为前景仅适用于文本块失去焦点的情况。如果您将我的问题作为答案回答:D 我可以将其标记为解决方案

标签: c# wpf xaml binding datacontext


【解决方案1】:

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

InitializeComponent();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多