将元素绑定到WPF

问题描述

我正在尝试使用以下方法将文本框绑定到.cs文件中定义的字符串:

Xaml代码

<TextBox x:Name="textBox_Data" CaretBrush="DodgerBlue" Foreground="White" Text="{Binding Data}" HorizontalAlignment="Left" Height="22" Margin="10,10,0" textwrapping="Wrap" VerticalAlignment="Top" Width="123" SelectionChanged="textBox_Data_SelectionChanged"/>

Xaml.cs代码

public string Data{get; set;}

但是字符串没有更新...

解决方法

您的类必须从INotifyPropertyChanged派生,并且您必须在属性设置器中实现它

或更轻松的方式:从nuget安装PropertyChanged.Fody。您可以在这里了解更多信息:https://github.com/Fody/PropertyChanged

请记住,初始化窗口时不要使用this.DataContext=this;,而应按照 vid 建议使用绑定。

,

{Binding Data}是指当前元素的DataContext(或祖先之一)。

单向

要引用xaml.xxx.cs,需要引用Window元素,可以给他起一个名字:

<Window x:Name="window" x:Class=...

,并更改绑定以引用元素名称:

Text="{Binding Data,ElementName=window}"

第二种方式

您还可以将所有窗口类注入当前的DataContext:

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" x:Class=...

现在您可以保留原始表达式:

Text="{Binding Data}"

第三种方式

您还可以从代码中设置DataContext。不要在xaml中进行任何更改,并在构造函数的末尾添加以下行(DataContext = this;):

 public xyz() {

     InitializeComponent();
     //...
     DataContext = this;
 }