在挂钩事件之前,WPF DataGrid未初始化

时间:2014-02-05 13:32:37

标签: c# wpf datagrid itemssource

我有一个简单的属性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>

1 个答案:

答案 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并且您收到错误..