2012-11-21 5 views
0

나는이 질문에 대한 몇 가지 대답을 찾았지만 어떻게 든 그것을 얻지는 못한다. 그러니 나 한테 물어봐.버튼을 어떻게 활성화/비활성화 할 수 있습니까?

MVVM 패턴을 따르는 WPF 응용 프로그램이 있습니다.

<button Content="Login" Command="{Binding ProjectLoginCommand}"/>

명령은 RelayCommand을 사용하고 있습니다 : 그것은보기 모델의 명령에 바인딩 된 버튼이 포함되어 있습니다. 이제 다음을 원합니다 :

  • 사용자가 버튼을 클릭하면 해당 명령이 실행됩니다. 이 작동합니다.
  • 이 명령 내에서 다른 버튼을 비활성화해야합니다. 즉, 클릭 할 수 없습니다.

나는 이것이 CanExecute을 사용하여 가능해야하지만 솔직히 말해서 나는 그것을 얻지 못한다. Hoe 버튼을 활성화/비활성화 할 수 있습니까?

RelayCommand.cs는 다음과 RelayCommand 오브젝트를 작성할 때 다른 중 (당신이 할 수있는 할 수있는 술어를 통과해야

RelayCommand getProjectListCommand; 

public ICommand GetProjectListCommand { 
    get { 
     if (getProjectListCommand == null) { 
      getProjectListCommand = new RelayCommand(param => this.ProjectLogin()); 
     } 
     return getProjectListCommand; 
    } 
} 
+1

두 명령의'Execute' 및'CanExecute'에 대한 코드를 표시 할 수 있습니까? – Rachel

+0

명령 사용법을 추가했습니다. 하지만 실제로,'RelayCommand' 클래스의 코드를 제외하고는'Execute' 나'CanExecute' 코드를 가지고 있지 않습니다. –

+0

감사합니다. Robert. Button의 Enabled/Disabled는 자동적으로'Command.CanExecute'에 묶여 있으므로 Button1은'CanButton2Execute'가 실행될 때 false가되도록 설정해야합니다. 그러면 Button2가 비활성화됩니다. – Rachel

답변

1

RelayCommand를 사용할 때 두 가지 방법을 지정할 수 있습니다. 첫 x 째 f}은 명령이 호출 될 때 실행할 기본 메소드입니다. 유효성 검사와 같은 검사에 추가하는 두 번째 방법은 bool을 반환해야합니다. false를 반환하면 main 메서드가 실행되지 않습니다.

명령이 바인딩 된 단추에 미치는 영향은 계속 부울 메서드를 실행하고 false를 반환하는 동안 명령이 바인딩 된 단추는 비활성화됩니다. 명령 속성에 따라서

:

public ICommand GetProjectListCommand { 
get { 
    if (getProjectListCommand == null) { 
     getProjectListCommand = new RelayCommand(param => this.ProjectLogin(), CanProjectLogin()); 
    } 
    return getProjectListCommand; 
} 

새로운 방식으로 추가

public bool CanProjectLogin() 
{ 
    //here check some properties to make sure everything is set that you'd want to use in your ProjectLogin() method 
} 

당신이 부울 방법에 브레이크 포인트를 넣어 경우 CanExecute가 어떻게 작동하는지 볼 수 있습니다.당신이 canExecute 콜백 작업에 문제가있는 경우

+0

이 설명은 나를 이해할 수있게합니다 :-) 그러나 param => 문은 두 번째 매개 변수에 대해 누락되었습니다. –

3

:

namespace MyApp.Helpers { 
    class RelayCommand : ICommand { 

    readonly Action<object> execute; 
    readonly Predicate<object> canExecute; 

    public RelayCommand(Action<object> execute) : this(execute, null) { 
    } 

    public RelayCommand(Action<object> execute, Predicate<object> canExecute) 
    { 
     if (execute == null) 
      throw new ArgumentNullException("execute"); 

     this.execute = execute; 
     this.canExecute = canExecute;   
    } 

    public bool CanExecute(object parameter) 
    { 
     return canExecute == null ? true : canExecute(parameter); 
    } 

    public event EventHandler CanExecuteChanged 
    { 
     add { CommandManager.RequerySuggested += value; } 
     remove { CommandManager.RequerySuggested -= value; } 
    } 

    public void Execute(object parameter) 
    { 
     execute(parameter); 
    } 
} 
} 

이 내가 명령을 호출하는 방법입니다 사물) 다음 서명이있는 메소드 :

bool MethodName (객체 매개 변수).

매개 변수가 필요하지 않으면 예 : MethodName()을 bool하지만 RelayCommand 생성자에 전달합니다. (o) => MethodName().

이 방법에서는 논리를 수행하고 명령을 실행할 수 있는지 여부를 나타내는 값을 반환해야합니다. 나머지는 WPF 명령 인프라로 처리해야합니다.

+0

지정하는 것을 잊었습니다 : 생성자에서 두 번째 인수로 조건자를 전달하십시오 : 새로운 relayCommand (param => this.ProjectLogin(), param => this.MethodName()) –

+0

감사합니다. emybobs와 결합하여이 주석은 그것은 맞습니다 :-) –

1

, 당신은 쉽게 RelayCommand의 간단한 버전으로 작업을 찾을 수 있습니다 :이 방법으로

class RelayCommand : ICommand 
{ 
    readonly Action execute; 
    private bool canExecute; 

    public RelayCommand(Action execute) 
    { 
     this.execute = execute; 
     this.canExecute = true; 
    } 

    public bool CanExecute(object parameter) 
    { 
     return canExecute; 
    } 

    public void SetCanExecute(bool canExecute) 
    { 
     this.canExecute = canExecute; 
     var handler = CanExecuteChanged; 
     if (handler != null) handler(this, EventArgs.Empty); 
    } 

    public event EventHandler CanExecuteChanged; 

    public void Execute(object parameter) 
    { 
     execute(); 
    } 
} 

, 당신은 당신이 할있는 오브젝트 RelayCommand에 대한 참조를 저장, 다음과 같은 명령을 비활성화 할 수 있습니다 :

getProjectListCommand.SetCanExecute(false); 
관련 문제