Search code examples
c#wpfdata-bindinginotifypropertychanged

What's wrong with the simplest Data-binding with WPF without using `INotifyPropertyChanged` or `DependencyProperty`


I'm just been playing with Data Bindings in WPF (I'm new to all this) and the following code is the simplest implementation that I can get to work. Code below:

My question is: Why would I need to use INotifyPropertyChanged and all the boilerplate code that comes with it or DependencyProperty etc when the simple below works just fine out of the box? I'm trying to understand why the examples and answers on this site are far more complicated that the example below.

My XAML

<TextBox Text="{Binding ConduitWidth, Mode = TwoWay}" />
<TextBox Text="{Binding ConduitWidth, Mode = TwoWay}" />

My Code-behind

public partial class ConduitCapacityCalculator : UserControl
{

    ConduitCapacity conduitCapacity = new ConduitCapacity();
    public ConduitCapacityCalculator()
    {
        InitializeComponent();
        this.DataContext = conduitCapacity;
        conduitCapacity.ConduitWidth = 10; //Just to check the textboxes update properly
    }
}

And my Class

public class ConduitCapacity
{
    private double _conduitWidth;

    public double ConduitWidth
    {
        get { return _conduitWidth; }
        set { _conduitWidth = value; } //add any conditions or Methods etc here
    }
}

Solution

  • Because Mode = TwoWay is not true in your example.

    Without any signalling (INotifyPropertyChanged) from the Source you are only getting OneWayToSource + OneTime modes.

    To test this, add a button and make it do: conduitCapacity.ConduitWidth = 100;

    See if you get that 100 in your Control.