c# - 从 XAML 到代码隐藏的数据绑定(bind)

标签 c# .net wpf data-binding binding

我在后面的代码中有这个 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/

相关文章:

c# - 仅当目标对象在 Automapper 中没有值时如何映射

c# - 如何防止在 WPF DataGrid 中取消选择?

c# - WPF 页面调整大小

c# - 延伸到列表框宽度但不超过宽度的列表框项目

C# 线程 ListView

c# - 在 C# 进程之间共享对象的推荐方式

.net - 什么是托管 C++ 等效于 C# using 语句

c# - WPF Datagrid 未正确显示数据但在单击列标题时正确显示

c# - 在 c# 中将字符串转换为 xml 会出现空白错误

c# - 如何使路由只能从本地主机访问?