无法将 属性 绑定到 WPF 标签

Unable to bind property to WPF label

我正在尝试将标签的内容绑定到我的 class 之一中的 属性 的值。当 属性 的值改变时,我希望它改变标签的内容。

这是我的位置 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";
    }
 }

这里是 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>

我在这里做错了什么导致它不使用 属性 的值更新标签内容?

你还需要设置局部变量town:

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

编辑:

Window

DataContext 尚未设置,因此需要设置 Binding 才能正常工作。

XAML:

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

代码:

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

它没有加注因为

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

首先:你需要给私有字段赋值town.

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

第二个: 在构造函数中你需要更新 public 属性 Town 而不是私有字段,所以 OnPropertyChanged 可以触发

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

编辑:

第三: 你的 Xaml 没有显示数据绑定的任何来源,你可以设置它,例如,在后面的代码中(因为你是此处不遵循 MVVM):

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