简体   繁体   中英

How to data-bind a label

How to bind the content of a label to the class2 property PropName ?
Class2 is not directly being used in Mainwindlow.xmal.cs .

Class1 is being used in Mainwindow.xmal.cs
And Class2 is being used in Class1 .
Here is the code I'm using:

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();            
    }
}

I want to bind the content of a label eith the Class2 property - PropName .
How can I do that?

Try this. XAML

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

On your WindowLoad set DataContext for Label .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM