Ci-dessous un exemple d'application simple. La case à cocher dans le ItemTemplate a une commande de liaison qui semble être à l'origine du problème. Lorsque j'essaie de l'exécuter, j'obtiens une exception NullReferenceException (à Microsoft.Practices.Composite.Presentation.Commands.DelegateCommand`1.System.Windows.Input.ICommand.CanExecute ...). Pourquoi cela arrive-t-il?CheckBox dans ItemTemplate provoque NullReferenceException pour la liaison de commande
MainWindow.xaml:
<Window x:Class="CheckBoxCommandTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel x:Name="stackPanel">
<ItemsControl ItemsSource="{Binding CheckBoxes}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}"
IsChecked="{Binding IsSelected}"
Command="{Binding DataContext.CheckBoxCommand, ElementName=stackPanel}"
CommandParameter="{Binding Parameter}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
CheckBoxCommand = new DelegateCommand<int>(OnCheckBoxChecked);
CheckBoxes = new List<CheckBoxModel>()
{
new CheckBoxModel { Name = "Checkbox #1", Parameter = 1 },
new CheckBoxModel { Name = "Checkbox #2", Parameter = 2 },
};
TriggerPropertyChanged("CheckBoxes");
}
public List<CheckBoxModel> CheckBoxes { get; set; }
public ICommand CheckBoxCommand { get; set; }
private void OnCheckBoxChecked(int i) { /* Do nothing */ }
}
CheckBoxModel.cs
public class CheckBoxModel
{
public string Name { get; set; }
public bool IsSelected { get; set; }
public int Parameter { get; set; }
}
Ça l'a fait! Merci! –