来自 ViewModel 的绑定字符串值未在 UI 元素中更新

Bound string value from ViewModel not updating in UI element

我在 XAML 中有这个 TextBlock,它的文本 属性 绑定到视图模型命令。

<TextBlock Text="{Binding SomeText}"></TextBlock>

同时,视图模型如下所示:

\ the text property
private string _someText = "";

public const string SomeTextPropertyName = "SomeText";
public string SomeText
{
    get
    {
        return _someText;
    }
    set
    {
        Set(SomeTextPropertyName, ref _someText, value);
    }
}

\ the command that changes the string

private RelayCommand<string> _theCommand;

public RelayCommand<string> TheCommand
{
    get
    {
        return _theCommand
            ?? (_theCommand = new RelayCommand<string>(ExecuteTheCommand));
    }
}

private void ExecuteTheCommand(string somestring)
{
    _someText = "Please Change";
    \ MessageBox.Show(SomeText);
}

我可以成功调用 TheCommand,就像我能够从触发元素使用该命令调用 MessageBox 一样。 SomeText 值也会更改,如注释的 MessageBox 行所示。我在这里做错了什么,有什么愚蠢的错误吗?

您正在直接设置字段 _someText,这意味着您绕过了 SomeText 属性 的 setter。但是 setter 正在调用内部引发 PropertyChanged 事件的 Set(SomeTextPropertyName, ref _someText, value); 方法。

数据绑定需要 PropertyChanged 事件,以便它知道 SomeText 属性 已更新。

这意味着,而不是这样做:

private void ExecuteTheCommand(string somestring)
{
    _someText = "Please Change";
    \ MessageBox.Show(SomeText);
}

只需执行此操作即可:

private void ExecuteTheCommand(string somestring)
{
    SomeText = "Please Change";
    \ MessageBox.Show(SomeText);
}