WPF 简单绑定代码隐藏
WPF simple bind in code behind
我正在尝试学习WPF,我的基本绑定有问题,一开始我想在后面的代码中设置绑定。谁知道我做错了什么?
菲尔斯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));
}
}
}
文件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
是根据当前绑定源设置的。您的来源(String
)没有 Content
属性。您可以将 Source
设置为 Window
,将 Path
设置为 MyText
var bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("MyText");
我正在尝试学习WPF,我的基本绑定有问题,一开始我想在后面的代码中设置绑定。谁知道我做错了什么?
菲尔斯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));
}
}
}
文件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
是根据当前绑定源设置的。您的来源(String
)没有 Content
属性。您可以将 Source
设置为 Window
,将 Path
设置为 MyText
var bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("MyText");