我在.xaml中创建了一个文本块,并在名为WrodName的.cs文件中声明了一个属性。我如何用textblock绑定该属性。我需要我们在标记的xaml代码中编写的代码,即DataContext代码。直到现在我想到了这个
<TextBlock Text="{Binding WordName}"/>
在.cs文件中:
public String WordName { get; set; }
从xaml设置DataContext:
<Window x:Class="ApplicationName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
但是在这种情况下,您必须在Initialize()之前分配值:
WordName = "word";
InitializeComponent();
或从这样的代码背后:
this.DataContext = this;
但是无论如何,我建议您将MVVM体系结构与INOtifyPropertyChanged事件一起使用。在这种情况下,只要将属性设置为新值,UI就会更新。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句