2014-02-05 85 views
0

我有一个简单的属性的getter返回无论是数据网格内的TabbedPanelWPF的DataGrid不挂钩事件

private DataView ActiveGrid 
    { 
     get 
     { 
      switch (TabPanel.SelectedIndex) 
      { 
       case 0: return (DataView)Grid1.ItemsSource; 
       case 1: return (DataView)Grid2.ItemsSource; 
      } 
      return null; 
     } 
    } 

curretly选择,但初始化之前,当我尝试调用它像这样

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

@HighCore - 哇,多么糟糕的评论。 – user1021726

回答

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; 
    } 
} 

在上面的代码中,你已经检查了如果(TabPanel.IsInitialized)。问题是与TabControl ..它不会被初始化在Ctor ...所以吸气剂返回null,你得到了错误..

+0

这是遗留代码,不再存在。我会更新我原来的问题。 – user1021726

+0

是TabPanel是加载? – Sankarann