【问题标题】:How to bind a Control.Property to a property in the code-behind?如何将 Control.Property 绑定到代码隐藏中的属性?
【发布时间】:2010-12-16 15:19:10
【问题描述】:

我的 WPF 窗口中有一个文本框。

我在后面的代码中也有一个名为 Text 的属性。

我希望将 text 属性绑定到 Text 属性(即,当属性中的值更改时,文本框的值也应该更新。

谢谢

【问题讨论】:

  • 您的问题的标题令人困惑,因为描述中没有布尔属性。
  • 我编辑了标题。谢谢。

标签: wpf binding wpf-controls code-behind


【解决方案1】:

您必须将 TextBox 控件(或其任何父控件)的 DataContext 设置为您的窗口:

myTextBox.DataContext = this;

然后在您的 XAML 中:

<TextBox Text={Binding Text} x:Name="myTextBox"/>

【讨论】:

  • 该属性是否必须是 DependencyProperty?
  • 根据您的 Text 属性(应该是 DependencyProperty)的声明,您可能需要显式设置 TwoWay 绑定:{Binding Text, Mode=TwoWay}
  • 可以是DependencyProperty(使用Visual Studio中的propdp代码sn-p)或者对象可以实现INotifyPropertyChanged接口。
  • 我实际上并不需要它作为两种方式,我只希望在更改 Window.Text 时更新 TextBox.Text。
  • 如果您将 Window.Text 定义为 DependencyProperty,则 TextBox.Text 将自动更新。 DP 定义示例: public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(Window), new UIPropertyMetadata(string.Empty));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 2011-01-01
  • 2016-09-05
  • 2013-10-17
  • 2012-02-04
  • 2011-04-22
相关资源
最近更新 更多