加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:55:10 所属栏目:百科 来源:网络整理
导读:我在代码背后有这个Text依赖属性: public static DependencyProperty TextProperty = DependencyProperty.Register("Text",typeof(string),typeof(MainWindow),new PropertyMetadata("Hello world"));public string Text { get { return (string)GetValue(T
我在代码背后有这个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}">

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读