我有一个简单的属性getter,它返回在TabbedPanel中当前选择的任何数据网格
private DataView ActiveGrid
{
get
{
switch (TabPanel.SelectedIndex)
{
case 0: return (DataView)Grid1.ItemsSource;
case 1: return (DataView)Grid2.ItemsSource;
}
return null;
}
}
但是当我尝试像这样调用它时
private void TabPanel_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updateIndex("{0} Items", ActiveGrid.Count);
}
它会引发InvokationTargetException
内部NullReferenceException
。那么ItemsSource没有初始化?嗯..?因为在我的MainWindow
构造函数中,我将ItemsSource设置为Grid1.ItemsSource = myDataTable();
我的XAML看起来像这样
<TabControl x:Name="TabPanel"
Margin="0,155,0,28"
SelectedIndex="0" SelectionChanged="TabPanel_SelectionChanged">
<TabItem x:Name="Grid1Tab" Header="Grid1" >
<DataGrid x:Name="Grid1"
AutoGenerateColumns="True"
Background="#FFE5E5E5"
ColumnWidth="*"/>
</TabItem>
<TabItem x:Name="Grid2Tab" Header="Grid2">
<DataGrid x:Name="Grid2"
AutoGenerateColumns="True"
Background="#FFE5E5E5"
ColumnWidth="*"/>
</TabItem>
</TabControl>
答案 0 :(得分:0)
private DataView ActiveGrid
{
get
{
if (TabPanel.IsInitialized)
{
switch (TabPanel.SelectedIndex)
{
case 0: return (DataView)Grid1.ItemsSource;
case 1: return (DataView)Grid2.ItemsSource;
}
}
return null;
}
}
在上面的代码中,您检查了 if(TabPanel.IsInitialized)。问题出在TabControl
..它不会在Ctor
中初始化...所以getter返回null
并且您收到错误..