Reputation: 26952
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
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
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