无法将属性绑定到WPF标签

crm*_*ham 1 c# wpf

我试图将标签的内容绑定到我的一个类中的Property的值.当Property的值发生变化时,我希望它改变标签的内容.

这是我的Location类:

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";
    }
 }
Run Code Online (Sandbox Code Playgroud)

这是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>
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么,是因为它没有使用Property的值更新标签内容?

toa*_*akz 8

您仍然需要设置局部变量town:

private String town;
public String Town
{
    get { return town; }
    set 
    {
        town = value;
        OnPropertyChanged("Town");
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

DataContextWindow尚未设定,因此需要在为了使Binding正常工作.

XAML:

<Window xmlns:local="clr-namespace:WeatherApplication" ....>
  <Window.DataContext>
      <local:Location/>
  </Window.DataContext>
  ....
</Window>
Run Code Online (Sandbox Code Playgroud)

码:

public MainWindow()
{
   InitializeComponent();
   this.DataContext = new Location(); 
}
Run Code Online (Sandbox Code Playgroud)