2013-10-29 69 views
0

我在我的視圖Home.xaml中有以下按鈕。我將它綁定到名爲StartStopLabel的屬性。我在相同的視圖中實現了接口ICommand,點擊Start後我可以將標籤更改爲文本「Stop」(這是我在視圖的構造函數中設置的初始狀態,如this.StartStopLabel="Start",this.ButtonStatus="click on start button"),但我不是能夠做相反的操作,即將按鈕的標籤從「停止」更改爲「開始」。我的意思是說ICommand當按鈕標籤顯示「停止」時不會收到點擊事件通知。如何在xaml中使用ICommand更改按鈕的標籤?

一旦用戶點擊「停止」按鈕(即當按鈕標籤顯示文本「停止」時)我想要將文本塊「BtnSTatus」的文本更改爲「您已經點擊了開始按鈕」並返回到「點擊開始按鈕」當按鈕標籤再次顯示文本「開始」時

有什麼建議如何解決這兩個問題?

筆者認爲:

<Button Name="btnStartStop" Content="{Binding StartStopLabel}" Command="{Binding ClickCommand}" /> 
<TextBlock Name="BtnStatus" Content="{Binding ButtonStatus}"> 

View.Cs代碼:

private string _startStopLabel; 
    public string StartStopLabel 
    { 
     get 
     { 
      return _startStopLabel; 
     } 
     set 
     {     
      _startStopLabel = value;     
      RaisePropertyChanged("StartStopLabel"); 
     } 
    } 

    private string _ButtonStatus; 
    public string ButtonStatus 
    { 
     get 
     { 
      return _ButtonStatus; 
     } 
     set 
     {     
      _ButtonStatus = value;     
      RaisePropertyChanged("ButtonStatus"); 
     } 
    } 

點擊指令事件,這是在View.cs的ICommand實現的一部分:我建議

public System.Windows.Input.ICommand ClickCommand 
    { 
     get 
     { 
      return new DelegateCommand((o) => 
      { 
       this.StartStopLabel = "Stop"; 
       Task.Factory.StartNew(() => 
       { 
        //call service on a background thread here... 

       }); 
      }); 
     } 
    } 
+1

你設置了DataContext = this?綁定區分大小寫。 ButtonStatus(在你的RaisePropertyChanged中)與ButtonSTatus(在你的XAML中)不是一回事。它看起來像只在點擊時將StartStopLabel文本設置爲停止。你永遠不會將其重置爲開始。 –

+0

是的,datacontext已正確設置並使用ButtonStatus更新了錯字。 – krrishna

回答

3

您的問題是屬性,都會評估你將不得不產生一個新的命令

public System.Windows.Input.ICommand ClickCommand 
{ 
    get 
    { 
     return new DelegateCommand(.... 

基本上每個時間英寸所以你必須遵守的命令將不會與你正在改變狀態的命令一樣。

更改您的實現以提前創建命令並返回相同的命令。

private System.Windows.Input.ICommand _clickCommand = new DelegateCommand((o) => 
     { 
      this.StartStopLabel = "Stop"; 
      Task.Factory.StartNew(() => 
      { 
       //call service on a background thread here... 

      }); 
     }); 
public System.Windows.Input.ICommand ClickCommand { get { return _clickCommand; }} 

此外,你通常會看到創建_clickCommand爲Lazy<ICommand>,使其只拿到第一次使用創建的模式。

+0

在上面的代碼中,您的硬編碼值爲「Stop」。您如何知道用戶點擊了哪個按鈕(開始或停止),以便您可以將其更改爲從停止開始或從開始停止? – krrishna

+1

@krrishna您可以檢查按鈕的文本或保持內部狀態。 –

+0

@MillieSmith我會去檢查按鈕的文本,那時使用屬性StartStopLabel將其更改爲從停止開始或從開始停止。 – krrishna

1

更改ClickCommand屬性,以便返回不同的命令以啓動和停止不同的文本:

  1. ClickCommand用Start命令初始化。
  2. 用戶執行命令。
  3. 啓動動作通過ICommand.Execute執行。
  4. ClickCommand更改爲返回停止命令。爲ClickCommand引發OnPropertyChanged,以便UI綁定到新命令。
  5. 用戶執行命令。
  6. 停止動作通過ICommand.Execute執行。
  7. ClickCommand更改爲返回開始命令。爲ClickCommand引發OnPropertyChanged,以便UI綁定到新命令。 ...
+0

我喜歡這個(我贊成它),但它仍然不回答他爲什麼不更新的問題。 –

+0

如果你能告訴我如何改變這個代碼來做同樣的事,那將是非常好的。 – krrishna

+0

你是對的。不知何故,我記得ICommand接口也有一個不屬於這種情況的文本屬性。所以答案並不能解決問題。 – Markus