[英]WPF simple bind in code behind
I try to learn WPF, I have problem with basic binding, at the beginning I want to set bind in code behind. 我尝试学习WPF,基本绑定有问题,一开始我想在后面的代码中设置绑定。 May anyone know what I make wrong?
谁能知道我做错了什么?
Fils CS 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 文件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>
Path
is set in relation to current binding source. 相对于当前绑定源设置了
Path
。 Your source (which is a String
) does not have Content
property. 您的源(是
String
)没有Content
属性。 You can set Source
to Window
and Path
to MyText
您可以将
Source
设置为Window
,将Path
为MyText
var bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("MyText");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.