WPF MVVM无法通过单击按钮来更新UI

时间:2020-07-30 10:54:46

标签: c# wpf mvvm

我有一个带有文本框和按钮的简单窗口。文本框绑定到名为“消息”的ViewModel属性,而按钮绑定到使用标准“ RelayCommand”的命令“ ClickCommand”。想法是单击按钮将更新文本框中的文本。

这里是绑定:

    <Button x:Name="button"  Command="{Binding ClickCommand}" Content="Button" HorizontalAlignment="Left" Margin="50,245,0,0" VerticalAlignment="Top" Width="75"/>
    <TextBox x:Name="textBox" Text="{Binding Message, Mode=OneWay}" HorizontalAlignment="Left" Height="23" Margin="50,95,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="650"/>

这是ViewModel:

public class ProgressViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public RelayCommand ClickCommand { get; set; }
    private ProgressModel progress;

    public ProgressModel Progress
    {
        get { return progress; }
        set { progress = value; OnPropertyChanged(); }
    }

    public ProgressViewModel()
    {
        progress = new ProgressModel { Message = "START" };
        ClickCommand = new RelayCommand((p) => UpdateMessage());
    }

    private void UpdateMessage()
    {
        // Gets to here OK ...
        Message = System.DateTime.Now.ToString(); 
    }

    public string Message
    {
        get
        {
            return progress.Message;
        }

        set
        {
            if (progress.Message != value)
            {
                OnPropertyChanged();
            }
        }
    }

    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

}

单击该按钮将成功地将我带到UpdateMessage(),但是Message属性未更改。即使我在此处放置一个断点并跨过它,“消息”值仍保持在“开始”位置,这是它在构造函数中初始化的值。 setter代码无法运行,OnPropertyChanged()不会触发,因此视图不会更新。

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您未设置Message的新值。

public string Message
{
    get
    {
        return progress.Message;
    }

    set
    {
        if (progress.Message != value)
        {
            progress.Message = value;
            OnPropertyChanged();
        }
    }
}
相关问题