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



我在XAML中有一个TextBlock,它的文本属性绑定到一个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行所示。我做错了什么,有什么愚蠢的错误吗?

您直接设置字段_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);
}

最新更新