2011-03-16 2 views
1

다음은 간단한 샘플 응용 프로그램입니다. 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; } 
} 

답변

2

이 가장 가능성이 일어나고을 매개 변수에 대한 바인딩과 함께 명령 매개 변수에 대한 유형을 입력합니다. 템플릿을 처음로드 할 때 Binding은 아직 평가되지 않았으므로 CommandParameter 속성 (object 유형)은 처음에는 null 값으로 할당됩니다 그것은 바운드 됨 (이 경우에는 단지 b efore the CommandParameter), DelegateCommand는 null 매개 변수를 int으로 사용하려고 시도합니다. 이는 매개 변수가 참조 유형이지만 일반적으로 int과 같은 값 유형에 대해서는 유효하지 않습니다.

매개 변수 유형을 int?으로 변경하고 명령 처리기에서 HasValue를 확인하여 오류를 수정할 수 있습니다.

+0

그랬어! 감사! –

0

명령이 실행되도록 허용되면 어쩌면 그 명령이 필요하지 않을 수 있습니다. 같은 DD 형식 :

개인 bool CanExecuteOnCheckBoxChecked (int notUsed) { return true; }

변화로 대표 :

CheckBoxCommand = 새로운 DelegateCommand (OnCheckBoxChecked, CanExecuteOnCheckBoxChecked); 개인 무효의

는 넣어 OnCheckBoxChecked :

을 경우 (CanExecuteOnCheckBoxChecked (I) { // 당신이 을 할 수 원하는대로 수행}이 값을 사용하고 있기 때문에

+0

감사합니다. 아니요, CanExecute가 필요하지 않습니다. 어쨌든 실패합니다. –

관련 문제