如何对标签进行数据绑定

本文关键字:数据绑定 标签 | 更新日期: 2023-09-27 18:10:12

如何将标签的内容绑定到class2属性PropName ?
2不直接用于Mainwindlow.xmal.cs

Class1被用于Mainwindow.xmal.cs
Class2Class1中使用。
下面是我使用的代码:

class Class2:INotifyPropertyChanged
{
    string _PropName;
    public string PropName
    {
        get
        {
            return this._PropName;
        }
        set
        {
            this._PropName = value;
            OnPropertyChanged("PropName");
        }
    }
    private void OnPropertyChanged(string p)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(p));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
public partial class MainWindow : Window,INotifyPropertyChanged
{
    Class1 class1ob;
    public MainWindow()
    {            
        InitializeComponent();
        class1ob = new Class1();          
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        class1ob.changeProp();            
    }
}

我想用Class2属性绑定标签的内容- PropName
我该怎么做呢?

如何对标签进行数据绑定

试试这个。XAML

....
<Label Name="label" Content="{Binding Path=PropName}"/>
....

WindowLoad上设置DataContextLabel

label.DataContext = class1ob.class2ob;//instance of class