c# - 如何根据按钮点击设置Label的内容

标签 c# wpf button mvvm label

我的 View 模型类中有一个方法,通过单击按钮调用并执行一些操作。现在我的 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" />

我的 View 模型:

    // 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 世界的新手。请帮忙!!!

最佳答案

将标签上的内容属性绑定(bind)到 View 模型上的属性。当您想要更新标签时,请更新响应属性。

查看

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

View 模型

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

关于c# - 如何根据按钮点击设置Label的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12720228/

相关文章:

jquery - 如何附加一个按钮,然后告诉该按钮删除 html 元素?

css - Bootstrap 4 边框重叠按钮元素

c#设置私有(private)变量的值

c# - 数据库预定操作

c# - 在 Windows XP 下通过远程桌面渲染 WPF 有问题吗?

c# - WPF 窗口上的细边框?

java - 通过 Button Action Listener 添加游戏的 JPanel(使用 KeyListener)会禁用 keylistener

c# - Dispose 中的成员变量访问

c# - 如何使用可执行文件打开文本文件?

c# - 没有setter的viewmodel中的WPF mvvm属性?