代码隐藏中的值更改时,Usercontrol未更新

时间:2017-04-09 19:24:12

标签: c# xaml data-binding

我有一个在运行时更新的viewmodel类。但是,如果在运行时代码隐藏中更改了viewmodel中的值,则不会更新视图。我哪里出错了?

viewmodel看起来像这样:

public class vmA : modelA, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChangedEventArgs.PropertyName));
    }

    public vmA ()
    {
        SomeValue = 254.43F; //This value is shown when the control is loaded
    }

    public void SetSomeValue(int _someValue)
    {
        SomeValue = _someValue; // If this is executed, the view still shows 254.43, even though _someValue contains a different value
    }
}

模型(由viewmodel继承)类看起来像这样

public class modelA : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChangedEventArgs.PropertyName));
    }

    private int someValue

    public int SomeValue
    {
        get { return someValue
        set { someValue value; OnPropertyChanged(new PropertyChangedEventArgs("SomeValue")); }                  
    }
}

绑定就像这样完成

<UserControl.DataContext>
    <vm:vmA></vm:vmA>
</UserControl.DataContext>

文本框绑定:

<TextBox x:Name="tbBetragNetto" Text='{Binding BetragNetto, Mode=TwoWay}' Grid.Column="0"/>

1 个答案:

答案 0 :(得分:1)

Because you have 2 INotifyPropertyChanged implementations. The binding is getting confused with which PropertyChanged event you want it to listen to. Shrink your view model to this:

public class vmA : modelA
{
    public vmA()
    {
        SomeValue = 254.43F; //This value is shown when the control is loaded
    }

    public void SetSomeValue(int _someValue)
    {
        SomeValue = _someValue; // If this is executed, the view still shows 254.43, even though _someValue contains a different value
    }
}