다음은 간단한 샘플 응용 프로그램입니다. ItemTemplate의 체크 박스에는 문제를 일으키는 것으로 보이는 명령 바인딩이 있습니다. 실행하려고하면 NullReferenceException이 발생합니다 (Microsoft.Practices.Composite.Presentation.Commands.DelegateCommand`1.System.Windows.Input.ICommand.CanExecute ...). 왜 이런 일이 생길까요?ItemTemplate의 CheckBox가 명령 바인딩에 NullReferenceException을 발생시킵니다.
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 나는 이것이 내가 항상 확인하는 CanExecute 방법을 사용했을
public class CheckBoxModel
{
public string Name { get; set; }
public bool IsSelected { get; set; }
public int Parameter { get; set; }
}
그랬어! 감사! –