Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this Text dependency property in code behind:

public static DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(MainWindow),
        new PropertyMetadata("Hello world"));

public string Text {
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}

I want to bind content of label to that Text property so that the label displays actual value of Text property and vice-versa.

<Label Content="{Binding ???}" />

How can I do it ?

I have done that some time before but now I cannot remember how - and it is very simple. The simplest code will be accepted.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

Set DataContext of your Window/Control to the same class and then specify the path on the binding, something like this:

public class MyWindow : Window {

    public MyWindow() {
        InitializeComponents();
        DataContext = this;
    }

    public string Text { ... }    
}

Then in your xaml:

<Label Content="{Binding Path=Text}">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...