数据绑定从XAML到后面的代码

我在代码后面有这个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); } } 

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

  

我该怎么做 ?

我已经做了一段时间了但是现在我不记得了 – 这很简单。 最简单的代码将被接受。

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

 public class MyWindow : Window { public MyWindow() { InitializeComponents(); DataContext = this; } public string Text { ... } }
public class MyWindow : Window { public MyWindow() { InitializeComponents(); DataContext = this; } public string Text { ... } } 

然后在你的xaml中:

 

您必须设置窗口的DataContext才能工作。 XAML:

         

代码隐藏:

 ///  /// Interaction logic for MainWindow.xaml ///  public partial class MainWindow : Window { public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MainWindow), new PropertyMetadata("Hello world")); public string Text { get { return (string)GetValue(TextProperty); } set { this.SetValue(TextProperty, value); } } public MainWindow() { InitializeComponent(); } protected void HandleClick(object sender, RoutedEventArgs e) { this.Text = "Hello, World"; } } 

当你说它在代码隐藏中时,你的意思是它在你的类窗口的代码中?

您可能希望绑定到祖先类型为Window的RelativeSource。 或者,如果尚未设置数据上下文,则在Load事件中,将窗口的DataContext属性设置为窗口本身(this),然后使用{Binding Text}。

将XAML中的DataContext设置为Code-Behind可能有点棘手但通常这些情况最常见:

  1. 您希望将DataContext设置为整个Window或Custom UserControl

  

要么

  

2.如果您将Window或用户控件的DataContext设置为后面的代码并且具有子控件,则需要将其DataContext设置为Code-Behind,您可以使用以下命令:

  

对于自定义UserControl

  

在这种情况下将DataContext设置为self,将使Binding引用Label对象本身而不是Control的Code-Behind。 我希望这会有所帮助。