2009-07-15 4 views
0

별도의 창에있는 2 개의 버튼에 동일한 사용자 지정 RoutedCommand를 사용하고 싶습니다.글로벌 사용자 지정 RoutedCommand를 정의하는 방법?

코드를 반복하지 않기 위해 앱의 어딘가에 명령을 정의하고 두 버튼에 모두 바인딩하려고합니다.

나는 그것을 달성하기 위해 스타일을 사용한다고 생각했습니다. 아래에서 간단한 샘플에서 문제를 재현합니다.

<Application.Resources> 
    <Style TargetType="{x:Type Window}"> 
     <Setter Property="CommandBindings"> 
     <Setter.Value> 
    <!--<Window.CommandBindings>--> <!--I tried with or without this. Doesn't change--> 
       <CommandBinding Command="{x:Static local:App.testBindingCommand}" 
        Executed="OnExecuted" CanExecute="OnCanExecute" /> 
     <!--</Window.CommandBindings>--> 
     </Setter.Value> 
     </Setter> 
    </Style> 
</Application.Resources> 

그리고 App.xaml.cs를에서 사용자 정의 명령 :

나는 App.Xaml의 스타일을 선언

public static RoutedCommand testBindingCommand = new RoutedCommand(); 

    private void OnExecuted(object sender, ExecutedRoutedEventArgs e) 
    { 
     System.Windows.MessageBox.Show("OnExecuted"); 
    } 

    private void OnCanExecute(object sender, CanExecuteRoutedEventArgs e) 
    { 
     System.Windows.MessageBox.Show("OnCanExecute"); 

     e.CanExecute = true; 
    } 

컴파일러는 코드를 좋아하고 오류를 제공하지 않습니다 :

오류 MC3080 : 속성 설정자 'CommandBindings'에 액세스 가능한 세트 접근자가 없으므로 설정할 수 없습니다.

AFAIK, Window 클래스에는 CommandBindings 속성이 있습니다.

1) 스타일을 사용하여 전역 명령 바인딩을 올바르게 선언 했습니까? 그렇지 않다면 어떻게 할 수 있습니까?

2) 스타일로 CommandBindings 속성을 설정할 수없는 이유는 무엇입니까?

감사합니다.

답변

1

속성 (값이 인)의 값을 CommandBinding의 인스턴스로 설정했기 때문에이 오류 메시지가 나타납니다. 속성에 setter가있는 경우에도 CommandBindingCommandBindingsCollection으로 설정할 수 없습니다.

<Window> 
    <Window.CommandBindings> 
     <CommandBinding Command="{x:Static local:App.testBindingCommand}" 
      Executed="OnExecuted" CanExecute="OnCanExecute" /> 
    </Window.CommandBindings> 
</Window> 

이이 CommandBindingCommandBindings 속성을 설정 오히려 WindowCommandBindings 컬렉션에 추가되지 않는다 :

정상적으로 커맨드 바인딩의 경우를 고려한다.

RoutedCommand을 사용해야합니까? 아마도 ICommand의 다른 구현을 사용하는 것이 더 나을 것입니다. 아마도 명령어가 실행될 때 delegate을 호출하는 구현 일 것입니다. Kent Boogaart에는 작동 할 수있는 DelegateCommand 구현이 있습니다 (다른 비슷한 구현이 주위에 떠 다니거나 직접 작성할 수도 있음).

+0

실제로 CommandBindingsCollection과 CommandBinding 간의 바인딩에 적합합니다. 그래서 를 처음 시도했습니다 (app.xaml의 주석 참조). DelegateCommand에서 lokk을 사용합니다. – rockeye

+0

맞았습니다. RelayCommand (또는 DelegateCommand)를 사용하는 것이 훨씬 더 쉽고 CommandBinding을 사용하지 않아도됩니다. 감사 – rockeye

관련 문제