【问题标题】:Bound string value from ViewModel not updating in UI element来自 ViewModel 的绑定字符串值未在 UI 元素中更新
【发布时间】:2020-02-19 09:14:42
【问题描述】:

我在 XAML 中有这个 TextBlock,它的 text 属性绑定到 viewmodel 命令。

<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 行中所示。我在这里做错了什么,有什么愚蠢的错误吗?

【问题讨论】:

    标签: xaml mvvm mvvm-light


    【解决方案1】:

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

    PropertyChanged 事件是数据绑定所必需的,因此它知道 SomeText 属性已更新。

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

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

    只要这样做,它应该可以工作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 2017-06-25
      • 2011-12-25
      相关资源
      最近更新 更多