【问题标题】:Adding Event Handlers to WPF DataGrid throws NullReferenceException将事件处理程序添加到 WPF DataGrid 会引发 NullReferenceException
【发布时间】:2011-11-11 23:53:44
【问题描述】:

我不确定我编写的 DataGrid 有什么问题。内容正确显示,但是当我尝试添加 OnSelectionChanged 事件处理程序时,奇怪的事情发生了。请帮助我!

首先,以下没有问题:

<DataGrid ItemsSource="{Binding XPath=services/service}" AutoGenerateColumns="False" Padding="2">
      <DataGrid.Columns>
          <DataGridTextColumn Header=" Service Name " Binding="{Binding XPath=name}" Width="300"/>
          <DataGridTextColumn Header=" Status " Binding="{Binding XPath=status}" />
      </DataGrid.Columns>
</DataGrid>

这里的服务/服务来自我的外部 XML 文件。我在文档中使用了 XmlDataProvider 资源。在那个 XML 中,一些“服务”标签有许多“服务”子元素;一些“服务”标签根本没有任何孩子(想知道这是否是问题的原因)。

所以结果 UI 是一些数据网格包含所有的行和列。一些数据网格只显示标题。

现在我补充一下:

<DataGrid ItemsSource="{Binding XPath=services/service}" AutoGenerateColumns="False" Padding="2"
SelectionChanged="DataGrid_SelectionChanged">

并在代码中放入一个空方法:

private void DataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {


    }

现在执行,抛出异常

System.NullReferenceException 未处理 Message=对象引用未设置为对象的实例。 来源=ForeFront 支持监视器 2 堆栈跟踪: 在 FSM.MainWindow.System.Windows.Markup.IStyleConnector.Connect(Int32 connectionId, Object target) 在 h:\Personal\Visual Studio 2010\Projects\ForeFront Support Monitor 2\ForeFront Support Monitor 2\MainWindow.xaml:line 42 在 System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader,XamlObjectWriter currentWriter) 在 System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter) 在 System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject 容器,IComponentConnector componentConnector,IStyleConnector styleConnector,List1 affectedChildren, UncommonField1 templatedNonFeChildrenField) 在 System.Windows.FrameworkTemplate.LoadContent(DependencyObject 容器,List`1 受影响的孩子)...

【问题讨论】:

标签: wpf xaml wpf-controls wpfdatagrid xmldataprovider


【解决方案1】:

XML 绑定到 WPF DataGrid 可能很麻烦。

尝试以不同的方式绑定 XML(如对象模型)...How to bind xml to the WPF DataGrid correctly?

然后检查选择更改事件是否正确触发?

【讨论】:

  • 非常感谢。但是,此事件处理程序不仅仅发生在 DataGrid 上。此 DataGrid 是 ListBox 元素的数据模板的一部分。当我在其他数据模板中添加事件处理程序时,也会出现同样的问题。
猜你喜欢
  • 1970-01-01
  • 2021-02-26
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多