Adding Event Handlers to WPF DataGrid throws NullReferenceException
I'm not sure what's wrong with the DataGrid I've written. The contents show up correctly but when I try to add in a OnSelectionChanged event handler, sth odd happens.Please help me!
Firstly, no problems below:
<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>
Here services/service are from my external XML file. I used XmlDataProvider resource in the document. In that XML, some 'services' tag has many 'service' children elements; some 'services' tag does not have any children at all (wondering if this is the cause of problem).
So the resultant UI is some of the datagrids contain all the rows and columns. some of the datagrids only show the headers.
Now I add in this:
<DataGrid ItemsSource="{Binding XPath=services/service}" AutoGenerateColumns="False" Padding="2"
SelectionChanged="DataGrid_SelectionChanged">
And put in a empty method on the code:
private void DataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
}
Now I execute, and an exception is thrown
System.NullReferenceException was unhandled Message=Object reference not set to an instance of an object. Source=ForeFront Support Monitor 2 StackTrace: at FSM.MainWindow.System.Windows.Markup.IStyleConnector.Connect(Int32 connectionId, Object target) in h:\Personal\Visual Studio 2010\Projects\ForeFront Support Monitor 2\ForeFront Support Monitor 2\MainWindow.xaml:line 42 at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter curr开发者_开发百科entWriter) at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter) at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List
1 affectedChildren, UncommonField
1 templatedNonFeChildrenField) at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)...
XML binding to WPF DataGrid can be torturous.
Try binding XML in a different way (like a object model)... How to bind xml to the WPF DataGrid correctly?
And then check if selection changed event fires correctly?
精彩评论