1

I needed a trivial example of how INotifyPropertyChanged is useful, but my demo app is going totally against my expectations.

namespace WpfApp2CS
{
    public class ViewModel
    {
        public double Value { get; set; }
    }
}


<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp2CS"
        Title="MainWindow" Width="300" Height="150"
        x:Class="WpfApp2CS.MainWindow">

    <Window.DataContext>
        <local:ViewModel />
    </Window.DataContext>

    <StackPanel>
        <Slider Value="{Binding Value, Mode=OneWayToSource}" />
        <TextBlock Text="{Binding Value, Mode=OneWay}" />
    </StackPanel>

</Window>

I was under the impression that the setter of Value would be hit every time the slider moves, but the getter would only be hit once because ViewModel doesn't raise INotifyPropertyChanged.PropertyChanged. This is not the case; the text updates with every movement of the slider.

Brandon Hood
  • 327
  • 2
  • 12
  • That's the power of XAML `DataBinding`, which causes the property in your example to stay in sync. If, however, the data is changed programmatically, the UI will not reflect the changes unless you implement `INotifyPropertyChanged`. – Funk Jun 23 '17 at 16:33
  • The `TextBlock` isn't updating for me when I try your example. That's because when the slider updates `Value`, no notification is raised, and so the binding on `TextBlock.Text` is not aware that it needs to update its target. If it updates for you, I suspect you pasted the wrong code into your question. – 15ee8f99-57ff-4f92-890c-b56153 Jun 23 '17 at 16:39
  • 2
    @EdPlunkett Works for me, I remember reading about this in [C# 6.0 and .NET 4.6](http://www.apress.com/us/book/9781484213339). After quick google search, also [this post](https://stackoverflow.com/questions/7767218/why-does-the-binding-update-without-implementing-inotifypropertychanged). – Funk Jun 23 '17 at 17:02
  • @Funk Wow, yes. I wasn't testing exactly the same thing after all, I just added a non-notifying property to a test viewmodel I had. It was I who had the wrong code! It works when I do it just as OP did. That is deeply weird. – 15ee8f99-57ff-4f92-890c-b56153 Jun 23 '17 at 17:08
  • Thanks @Funk! I had a feeling it was magic. – Brandon Hood Jun 23 '17 at 17:08
  • Always glad to enlighten :) – Funk Jun 23 '17 at 17:10

0 Answers0