如何根据按钮单击设置标签内容

时间:2012-10-04 04:21:11

标签: c# wpf button mvvm label

我的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 个答案:

答案 0 :(得分:2)

将标签上的content属性绑定到视图模型上的属性。如果要更新标签,请更新响应属性。

查看

<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);   
    }
  }

答案 1 :(得分:1)

您必须在代码后面创建Label对象,如下所示。

var lableMSG = new Lable();

lableMSG.Content = "Message string";
希望这会对你有帮助!!