2014-02-05 60 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