Mister 832
Mister 832

Reputation: 1221

Usercontrol not updated when value changes in codebehind

I have a viewmodel class that is update at runtime. However, if a value in the viewmodel is changed in the codebehind at runtime, the view is not updated. Where did I go wrong?

The viewmodel looks like this:

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
    }
}

The model (which is inherited by the viewmodel) class looks like this

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")); }                  
    }
}

The binding is done like this

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

The textbox binding:

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

Upvotes: 0

Views: 88

Answers (1)

Laith
Laith

Reputation: 6091

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
    }
}

Upvotes: 1

Related Questions