Reputation: 12053
I try to learn WPF, I have problem with basic binding, at the beginning I want to set bind in code behind. May anyone know what I make wrong?
Fils CS
public partial class BindInCodeBehind : Window, INotifyPropertyChanged
{
private string _myText;
public string MyText
{
get { return _myText; }
set
{
_myText = value;
OnPropertyChanged("MyText");
}
}
public BindInCodeBehind()
{
InitializeComponent();
var bind = new Binding();
bind.Source = MyText;
bind.Path = new PropertyPath("Content");
MyLabel.SetBinding(Label.ContentProperty, bind);
MyText = "New tekst";
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
File XAML
<Window x:Class="WpfBindingLearn.BindInCodeBehind"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BindInCodeBehind" Height="300" Width="300">
<Grid>
<Label Name="MyLabel" Content="Wait for binding"></Label>
</Grid>
</Window>
Upvotes: 0
Views: 166
Reputation: 33364
Path
is set in relation to current binding source. Your source (which is a String
) does not have Content
property. You can set Source
to Window
and Path
to MyText
var bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("MyText");
Upvotes: 2