2012-10-04 128 views
2

我在我的viewmodel類中有一個方法,通過點擊按鈕調用並執行一些操作。現在我有一個標籤和按鈕在我的XAML文件:如何設置基於按鈕的標籤內容點擊

<Label Content="" Height="20" HorizontalAlignment="Center" Margin="0,50,0,0" Name="label1" VerticalAlignment="Top" Width="119" /> 
<Button Content="Sync" Height="23" Command="{Binding Path=SyncCommand}" HorizontalAlignment="Center" Margin="0,15,0,0" Name="button1" VerticalAlignment="Top" Width="100" /> 

我的視圖模型:

// This method is called when Sync Button is Clicked 
    public void SyncCommandExecuted() 
    {    
     string strBadResp = string.Empty; 
     Byte[] sendBuf = new Byte[256]; 
     Byte[] readBuf = new Byte[256];   
     sendBuf[0] = 0x80; 
     mComm.setAddress(0x3e); 
     mComm.WriteBytes(4, sendBuf); 

     if (mComm.ReadBytes(4, ref readBuf) != 0) 
     {     
      for (int cnt = 0; cnt < 4; cnt++) 
      { 
       if (readBuf[cnt] != null) 
       { 
        sendBuf[cnt] = readBuf[cnt];       
       } 
       else 
       {       
        strBadResp = "Bad response"; 

        // Here I want to display the content in strBadResp i.e. BAD RESPONSE on a label 
        sendBuf = null;       
       } 
      } 

      if (sendBuf != null) 
      { 
       strBadResp = BitConverter.ToString(sendBuf); 

       // Here I want to display the content in strBadResp on a label 
      }     
     } 
    } 

我的ReadBytes方法存儲以下內容:

byteArray[0] = 0x01; 
byteArray[1] = 0x02; 
byteArray[2] = 0x03; 
byteArray[3] = 0x04; 

所以基本上在兩個地方結果(strBadResp)不能在標籤中。我希望我已經說清楚了。我是這個WPF世界的新手。請幫忙!!!

回答

2

將標籤上的內容屬性綁定到視圖模型上的屬性。當你想更新標籤時更新響應屬性。

查看

<Label Content="{Binding Response}" Height="20" HorizontalAlignment="Center" Margin="0,50,0,0" Name="label1" VerticalAlignment="Top" Width="119" /> 

視圖模型

public class YourViewModel : INotifyPropertyChanged { 

    string response; 

    public string Response { 

     get { return this.response; } 

     set { 
      if (this.response == value) 
       return; 

      this.response = value; 
      NotifyPropertyChanged("Response"); 
     } 
    } 

    public event NotityPropertyChangedEventHandler = delegate {} 

    void NotifyPropertyChanged(string propertyName) { 
     PropertyChanged(this, new PropertyChangedEventArgs(propertyName); 
    } 
    } 
+0

添加上面的代碼後,我只是添加Response = strBadResp;並且我得到了它:)謝謝Per。 –

1

您必須在後面的代碼中創建Lable對象,如下所示。

var lableMSG = new Lable(); 

lableMSG.Content = "Message string"; 

希望這會幫助你!

+0

我下面MVVM模式。烏爾回答不是我所期待的:( –

+0

雅它幫助我.. –