我在代码背后有这个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); }
- }
我想将标签的内容绑定到该Text属性,以便标签显示Text属性的实际值,反之亦然.
- <Label Content="{Binding ???}" />
我该怎么做 ?
我已经做了一段时间,但现在我不记得如何 – 而且很简单.最简单的代码将被接受.
解决方法
将Window / Control的DataContext设置为同一个类,然后指定绑定上的路径,如下所示:
- public class MyWindow : Window {
- public MyWindow() {
- InitializeComponents();
- DataContext = this;
- }
- public string Text { ... }
- }
然后在你的xaml:
- <Label Content="{Binding Path=Text}">