c# – 从XAML到代码的数据绑定

前端之家收集整理的这篇文章主要介绍了c# – 从XAML到代码的数据绑定前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在代码背后有这个Text依赖属性
  1. public static DependencyProperty TextProperty =
  2. DependencyProperty.Register("Text",typeof(string),typeof(MainWindow),new PropertyMetadata("Hello world"));
  3.  
  4. public string Text {
  5. get { return (string)GetValue(TextProperty); }
  6. set { SetValue(TextProperty,value); }
  7. }

我想将标签内容绑定到该Text属性,以便标签显示Text属性的实际值,反之亦然.

  1. <Label Content="{Binding ???}" />

我该怎么做 ?

我已经做了一段时间,但现在我不记得如何 – 而且很简单.最简单的代码将被接受.

解决方法

将Window / Control的DataContext设置为同一个类,然后指定绑定上的路径,如下所示:
  1. public class MyWindow : Window {
  2.  
  3. public MyWindow() {
  4. InitializeComponents();
  5. DataContext = this;
  6. }
  7.  
  8. public string Text { ... }
  9. }

然后在你的xaml:

  1. <Label Content="{Binding Path=Text}">

猜你在找的C#相关文章