Null reference exception caused by null command parameter?
Just a weird exception that I can't get my head around
My cod开发者_如何学运维e:
<ListBox Grid.Row="1" Grid.Column="0" Background="{StaticResource ContentBackgroundColour}" BorderThickness="0" Margin="0,3,0,3" ItemsSource="{Binding Path=Scenarios}" HorizontalContentAlignment="Stretch" Padding="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" HorizontalContentAlignment="Left" Command="{Binding Path=OpenScenario}" CommandParameter="{Binding}"></Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And:
public ICommand OpenScenario
{
get { return new RelayCommand(param => _OpenScenario((ManageScenarioModel)param),
param => ((ManageScenarioModel)param).IsOpen); }
}
private void _OpenScenario(ManageScenarioModel toOpen)
{
toOpen.IsOpen = true;
new ManageScenario(this).Show();
}
However the part param => ((ManageScenarioModel)param).IsOpen)
throws a null reference exception upon start up, can someone please explain why this is?
Because WPF is calling your "CanExecute" expression to determine whether or not the button should be enabled. Apparently your binding is resulting in a null command parameter. You should probably check for a null parameter and return false.
param => (param != null && ((ManageScenarioModel)param).IsOpen)
精彩评论