结合不更新时属性设置命令内(Binding doesn't update when prop

2019-10-30 03:21发布

我有试图让一个简单的事情工作了惊人的困难,也就是设置在通过绑定到一个按钮命令调用的方法的属性。

当我设置的视图模型构造属性,正确的值是正确显示在视图中,但是当我设置该属性用命令的方法,这个视图不更新,虽然我创建的任何断点达到(甚至里面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>

Answer 1:

Youdid填补接口实现把你没有提到它的基本视图模型。 你缺少这样: INotifyPropertyChanged连接接口的基类,这使视图刷新内容。



Answer 2:

你错过了声明ViewModelBase:INotifyPropertyChanged的上ViewModelBase



文章来源: Binding doesn't update when property is set inside a command