无法将属性绑定到WPF标签

时间:2015-01-28 13:39:20

标签: c# wpf

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

这是我的位置类:

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>

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

3 个答案:

答案 0 :(得分:8)

您仍需要设置本地变量town

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

修改

DataContext的{​​{1}}尚未设置,因此需要Window才能正常工作。

XAML:

Binding

代码:

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

答案 1 :(得分:1)

首先:您需要将值分配给私人字段town

public String Town
    {
        get { return town; }
        set 
        {
            town = value;
            OnPropertyChanged("Town");
        }
    }
在构造函数中

第二:,您需要更新公共属性Town而不是私有字段,因此可以触发OnPropertyChanged

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

修改:

第三:您的Xaml没有显示DataBinding的任何来源,您可以通过例如后面的​​代码设置它(因为您不在这里跟踪MVVM):< / p>

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

答案 2 :(得分:0)

这不是因为

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