Bogdan Verbenets
Bogdan Verbenets

Reputation: 26952

bind a control to a code-behind property of this object

I have a property in a code-behind class to which I want to bind my Label control:

    public MainWindow()
    {
        InitializeComponent();
        this.Label1Content = "some text";
    }

    public string Label1Content { get; set; }

But the binding fails. Obviously I am missing something in the binding configuration, but I don't know what. I know how to bind this property using C#, but how do I bind it using XAML and without declaring DataContext?

Upvotes: 0

Views: 544

Answers (2)

myermian
myermian

Reputation: 32525

You still have to declare a DataContext, even if it is the same control:

public MainWindow()
{
    InitializeComponent();

    DataContext = this;

    this.Label1Content = "some text";
}

Also, the control will have to implement INotifyPropertyChanged so you can raise the PropertyChanged event. You're property should be self-contained like so:

public string _lable1Content;
public string Label1Content
{
    get { return _label1Content; }
    set
    {
        if (Equals(value, _label1Content)) return;

        _label1Content = value;

        //However you decide to implement the RaisePropertyChanged method.
    }
}

Upvotes: 1

Adi Lester
Adi Lester

Reputation: 25211

If you don't want to declare a datacontext anywhere, you could use

<Label Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=Label1Content}" />

Upvotes: 1

Related Questions