我在后面的代码中有这个 Text
依赖属性:
public static DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MainWindow),
new PropertyMetadata("Hello world"));
public string Text {
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
我想将标签的内容绑定(bind)到 Text
属性,以便标签显示 Text
属性的实际值,反之亦然。
<Label Content="{Binding ???}" />
我该怎么做?
我以前做过,但现在我不记得是怎么做的了——而且很简单。最简单的代码将被接受。
最佳答案
将 Window/Control 的 DataContext 设置为同一个类,然后在绑定(bind)上指定路径,如下所示:
public class MyWindow : Window {
public MyWindow() {
InitializeComponents();
DataContext = this;
}
public string Text { ... }
}
然后在你的 xaml 中:
<Label Content="{Binding Path=Text}">
关于c# - 从 XAML 到代码隐藏的数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5824600/