Reputation: 1221
I am developing an application in WPF and from some reason Visual studio display in error window this exception: Object reference not set to an instance of an object
When I was building application this errors are still visible, but I application works correct
this is a my XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Margin="5"
HorizontalAlignment="Stretch" VerticalAlignment="Top" Orientation="Vertical">
<CheckBox Name="cbPersonType" Content="Person Type" IsChecked="{Binding Path=IsPersonTypeVisible, Mode=TwoWay}" />
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="1" Margin="5"
HorizontalAlignment="Stretch" VerticalAlignment="Top" Orientation="Vertical">
<DataGrid Name="dgPersons">
<DataGrid.Columns>
<DataGridTextColumn Width="*" Header="Person Type"
Visibility="{Binding Path=IsChecked, Source={x:Reference Name=cbPersonType}, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
this exception is on DataGridTextColumn. Does some one know why and what is this error?
Upvotes: 0
Views: 1040
Reputation: 1479
I would suggest to replace
Source={x:Reference Name=cbPersonType}
with ElementName=cbPersonType
. This works fine both in design and runtime modes
Upvotes: -1
Reputation: 43
This is just a theory from my part trying to explain the errormessage.
Right now I'm struggling with a similar case. However, I have my checkbox in a contextmenu displaying the columns in a datagrid. The user can check the columns he/she wants to see in the datagrid.
Problem is the checkboxes seem not to be initlized until the user actually right-click to open the contextmenu. Until then the datagrid just shows empty rows with no columns at all.
It seems the x:Reference does not kick in until the checkboxes are loaded in the contextmenu.
A simplified XAML of the contextmenu and datagrid is below.
<DataGrid ItemsSource="{Binding OrderCollection}" AutoGenerateColumns="False" IsReadOnly="True" >
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Columnsetup">
<CheckBox x:Name="chkHeadOrderNo" Content="Ordernumber" IsChecked="{Binding columnVisibilityHeadOrderNo}"/>
</MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding OrderNo}" Header="Ordernumber"
Visibility="{Binding Source={x:Reference chkHeadOrderNo}, Path=IsChecked, Converter={StaticResource convertVisibility}}"/>
</DataGrid.Columns>
</DataGrid>
Upvotes: 2