我有试图让一个简单的事情工作了惊人的困难,也就是设置在通过绑定到一个按钮命令调用的方法的属性。
当我设置的视图模型构造属性,正确的值是正确显示在视图中,但是当我设置该属性用命令的方法,这个视图不更新,虽然我创建的任何断点达到(甚至里面RaisePropertyChanged
在我ViewModelBase
)。 我使用香草RelayCommand
在线教程容易被发现(从约什-史密斯,如果我没有记错的话)。
我的项目可以下载这里 (Dropbox的);
一些重要的代码块都低于:
视图模型:
public class IdiomaViewModel : ViewModelBase
{
public String Idioma {
get { return _idioma; }
set {
_idioma = value;
RaisePropertyChanged(() => Idioma);
}
}
String _idioma;
public IdiomaViewModel() {
Idioma = "nenhum";
}
public void Portugues () {
Idioma = "portu";
}
private bool PodePortugues()
{
if (true) // <-- incluir teste aqui!!!
return true;
return false;
}
RelayCommand _comando_portugues;
public ICommand ComandoPortugues {
get {
if (_comando_portugues == null) {
_comando_portugues = new RelayCommand(param => Portugues(),
param => PodePortugues());
}
return _comando_portugues;
}
}
public void Ingles () {
Idioma = "ingle";
}
private bool PodeIngles()
{
if (true) // <-- incluir teste aqui!!!
return true;
return false;
}
RelayCommand _comando_ingles;
public ICommand ComandoIngles {
get {
if (_comando_ingles == null) {
_comando_ingles = new RelayCommand(param => Ingles(),
param => PodeIngles());
}
return _comando_ingles;
}
}
}
查看与后面没有额外的代码:
<Window x:Class="TemQueFuncionar.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:TemQueFuncionar"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<app:IdiomaViewModel/>
</Window.DataContext>
<StackPanel>
<Button Content="Ingles" Command="{Binding ComandoIngles, Mode=OneWay}"/>
<Button Content="Portugues" Command="{Binding ComandoPortugues, Mode=OneWay}"/>
<Label Content="{Binding Idioma}"/>
</StackPanel>
</Window>