Xaml 来自ViewModel的绑定字符串值未在UI元素中更新
我在XAML中有一个Xaml 来自ViewModel的绑定字符串值未在UI元素中更新,xaml,mvvm,mvvm-light,Xaml,Mvvm,Mvvm Light,我在XAML中有一个TextBlock,它的text属性绑定到一个viewmodel命令 <TextBlock Text="{Binding SomeText}"></TextBlock> 同时,viewmodel如下所示: \\ the text property private string _someText = ""; public const string SomeTextPropertyName = "SomeText"; public string
TextBlock
,它的text属性绑定到一个viewmodel命令
<TextBlock Text="{Binding SomeText}"></TextBlock>
同时,viewmodel如下所示:
\\ 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);
}
\\text属性
私有字符串_someText=“”;
public const string SomeTextPropertyName=“SomeText”;
公共字符串SomeText
{
得到
{
返回_someText;
}
设置
{
Set(SomeTextPropertyName,ref\u someText,value);
}
}
\\更改字符串的命令
私人住宅小区(小区);;
公共关系共同体
{
得到
{
返回命令
?(_theCommand=new RelayCommand(ExecuteTheCommand));
}
}
private void ExecuteTheCommand(字符串somestring)
{
_someText=“请更改”;
\\MessageBox.Show(SomeText);
}
我可以成功地调用
命令
,就像我使用触发元素中的该命令调用消息框一样。SomeText
值也会发生变化,如注释的MessageBox
行所示。我在这里做错了什么,有什么愚蠢的错误吗?您直接设置字段\u someText
,这意味着您通过传递someText
属性的setter。但是,setter调用Set(SomeTextPropertyName,ref usomeText,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);
}