L Briggs L Briggs - 3 months ago 19
Vb.net Question

VB.NET WPF Data Binding On Control Property (How to update)

im trying to learn how to use WPF data binding.

I have a control, and i want to change the value f a property in the control.

<somecontrol Value="{Binding GoodRange}">


I created the property in the MainWindow Class as follows:

Public Property GoodRange As Double
Get
Return m_GoodRange
End Get
Set(value As Double)
m_GoodRange = value
End Set
End Property
Private m_GoodRange As Double


Inside the Mainwindow class i added the following to the sub New()

Public Sub New()
InitializeComponent()
GoodRange = 3000
Me.DataContext = Me
End Sub


So far so good, hwen i launch the program the value 3000 is passed to the control.

Now, during runtime i want to change the property for example when a user clicks on a button, or on a timed event eg:

Private Sub UpdateValue()

GoodRange = 2800

End Sub


When i do this, the value on the control is not updated. im trying to understand how i can trigger the control to update.

I have googled for 4 hours try try and understand, and i have found and tried a lot of answers on google, but usually these answers are for custom controls or custom classes or using the .datacontex method which i cant use as multiple property's will need to be changed.

I would be greatfull for any help you guys can offer.

Thank you/

Answer

As Clemens says in the comment to your question, you really need to do some research on MVVM, which has Data Binding as its heart and soul. An excellent article to start is of course the classic from Josh Smith, MVVM Design Pattern

In the meantime, as a minimum functional example, you should create a class as shown below that implements the INotifyPropertyChanged interface (code below is in C#):

public class myViewModel : INotifyPropertyChanged
{

    private double goodRange = 3000;
    public double GoodRange
    {
        get
        {
            return goodRange;
        }
        set
        {
            if (value != goodRange)
            {
                goodRange = value;
                NotifyPropertyChanged("GoodRange");
            }
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

In the code behind of your window:

Dim mVM as myViewModel

Public Sub New()
   InitializeComponent()
   mVM = new myViewModel()
   Me.DataContext = mVM
End Sub

Private Sub UpdateValue()
   mVM.GoodRange = 2800
End Sub