Data binding UWP中的数据绑定
因为我是UWP的新手。 我需要将MainPage.Cs文件中的属性绑定到MainPage.xaml并显示数据。 请查找下面的代码 MainPage.xaml.csData binding UWP中的数据绑定,data-binding,uwp,Data Binding,Uwp,因为我是UWP的新手。 我需要将MainPage.Cs文件中的属性绑定到MainPage.xaml并显示数据。 请查找下面的代码 MainPage.xaml.cs public string ButtonText { get ; set ; } public MainPage() { ButtonText = "Blue"; this.InitializeComponent(); } Mainpage.Xaml <Grid
public string ButtonText { get ; set ; }
public MainPage()
{
ButtonText = "Blue";
this.InitializeComponent();
}
Mainpage.Xaml
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button Content="{Binding ButtonText}" />
</Grid>
按钮内容不会显示在输出中。您的问题是由于缺少DataContext造成的。每个绑定都由一个绑定目标和一个绑定源组成。通常,目标是控件或其他UI元素的属性,源是类实例(数据模型或视图模型)的属性。DataContext是绑定标记扩展将找到其源的位置。您可以将以下代码添加到代码隐藏中:
ButtonText = "Blue";
this.InitializeComponent();
//set the data context as itself.
this.DataContext = this;
另一种选择是可以使用x:bind标记扩展。它将自动将后面的代码视为DATACONTRON。
看起来是这样的:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<!-- don't need to change code in code-behind -->
<Button Content="{x:Bind ButtonText}" />
</Grid>
有关数据绑定的更多信息,请参阅本文档:和