crmepham
crmepham

Reputation: 4760

Unable to bind property to WPF label

I am attempting to bind the content of a label to the value of a Property in one of my classes. When the value of the Property changes I want it to change the content of the label.

Here is my Location class:

public class Location : INotifyPropertyChanged
{


    private String town;

    public String Town
    {
        get { return town; }
        set 
        {
            OnPropertyChanged(Town);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string Property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(Town));
    }

    public Location()
    {
      town = "test";
    }
 }

Here is the XAML:

<Window x:Class="WeatherApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Weather Application" Height="550" Width="850" Loaded="Window_Loaded" IsEnabled="True" ResizeMode="CanMinimize" Icon="/WeatherApplication;component/Images/weatherIcon.png">
    <Grid Height="522" Background="#FFE7E7E7">

        <Label Content="{Binding Town, Mode=OneWay}" Name="townLabel" />

    </Grid>
</Window>

What am I doing wrong here that is making it not update the label contents with the value of the Property?

Upvotes: 1

Views: 715

Answers (3)

AymenDaoudi
AymenDaoudi

Reputation: 8309

First : you need to assign the value to the private field town.

public String Town
    {
        get { return town; }
        set 
        {
            town = value;
            OnPropertyChanged("Town");
        }
    }

Second : in the constructor you need to update the public property Town not the private field, so the OnPropertyChanged can be triggered

public Location()
{
   Town = "test";
}

Edit:

Third : Your Xaml don't show any source for the DataBinding, you can set it by, for instance, in the code behind (since you are not following MVVM here) :

public MainWindow()
{
    InitializeComponent();
    This.DataContext = new Location();
}

Upvotes: 1

toadflakz
toadflakz

Reputation: 7934

You still need to set the local variable town:

private String town;
public String Town
{
    get { return town; }
    set 
    {
        town = value;
        OnPropertyChanged("Town");
    }
}

Edit:

DataContext of Window has not been set so it needs to be in order for the Binding to work correctly.

XAML:

<Window xmlns:local="clr-namespace:WeatherApplication" ....>
  <Window.DataContext>
      <local:Location/>
  </Window.DataContext>
  ....
</Window>

Code:

public MainWindow()
{
   InitializeComponent();
   this.DataContext = new Location(); 
}

Upvotes: 8

DevEstacion
DevEstacion

Reputation: 1977

It's not raising because

public Location()
{
  town = "test"; // You set'd on the field and not the property so it didn't raise
}

Upvotes: 0

Related Questions