从 XAML 到代码隐藏的数据绑定 [英] Databind from XAML to code behind

查看:21
本文介绍了从 XAML 到代码隐藏的数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在后面的代码中有这个 Text 依赖属性:

I have this Text dependency property in code behind:

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 属性的实际值,反之亦然.

I want to bind content of label to that Text property so that the label displays actual value of Text property and vice-versa.

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

我该怎么做?

我以前做过,但现在我不记得是怎么做的 - 而且很简单.最简单的代码将被接受.

I have done that some time before but now I cannot remember how - and it is very simple. The simplest code will be accepted.

推荐答案

将你的 Window/Control 的 DataContext 设置为同一个类,然后在绑定上指定路径,如下所示:

Set DataContext of your Window/Control to the same class and then specify the path on the binding, something like this:

public class MyWindow : Window {

    public MyWindow() {
        InitializeComponents();
        DataContext = this;
    }

    public string Text { ... }    
}

然后在您的 xaml 中:

Then in your xaml:

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

这篇关于从 XAML 到代码隐藏的数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆