Question

I have some issues with OnPropertyChanged.

On my View, I wrote:

<StackPanel>
     <Label Content="{Binding TestProperty, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
     <Button Content="Click me" Click="Button_Click" />
</StackPanel>

This Data Context is:

class MainWindowViewModel : PropertyChangedBase
{
    public string TestProperty
    {
        get
        {
            if (TestWrapperModel.Instance.TestModel == null)
                return "Test Initial String";
            return TestWrapperModel.Instance.TestModel.TestProperty;
        }
    }
}

My TestWrapperModel is just a simple singleton wrapper that implements PropertyChangedBase.

My TestModel is like:

class TestModel : PropertyChangedBase
{
    private String _testProperty= "";

    public String TestProperty
    {
        get
        {
            return _testProperty;
        }
        set
        {
            _testProperty= value;
            OnPropertyChanged("TestProperty");
        }
    }
}

PropertyChangedBase is an abstract class that implements INotifyPropertyChanged interface.

Whenever I change the value of TestProperty, OnPropertyChanged fires, but the label on the UI doesn't show the new value (So it always display "Test Initial String"). Snoop says the binding works.

I think it's a simple problem and I just can't see what the problem is. Do you have any idea?

Was it helpful?

Solution 2

It won't work, since you DataContext is your MainWindowViewModel class, and not your TestModel class. When the application starts, it gets the value from TestProperty only once, and if doesn't change it won't change the label's value.

You should write the set on your TestProperty on the MainWindowViewModel to change your label.

OTHER TIPS

You need to propagate the event from the child viewmodel to the parent viewModel.

Subscribe to the PropertyChanged event of TestModel and raise a further PropertyChanged event in your MainWindowViewModel class to notify the view that the TestProperty property has changed.

The PropertyChanged event fires on the model, but you are binding on the viewmodel. If the latter doesn't invoke its own PropertyChanged event the binding engine doesn't know that things have changed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top