0

I've got a simple property getter which returns whatever datagrid is curretly selected within a TabbedPanel

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

But when I try to invoke it like this

    private void TabPanel_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        updateIndex("{0} Items", ActiveGrid.Count);
    }

it throws an InvokationTargetException with an inner NullReferenceException. So the ItemsSource is not initialized? Hmm..? Because in my MainWindow constructor I set the ItemsSource like so Grid1.ItemsSource = myDataTable();

My XAML looks like this

    <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>
user1021726
  • 638
  • 10
  • 23

1 Answers1

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

in the Above code, you have checked the if (TabPanel.IsInitialized). The problem is with TabControl.. it will not be Initialized in the Ctor... so the getter returns null and you got the error..

Sankarann
  • 2,625
  • 4
  • 22
  • 59