提示:以下是本篇文章正文内容,下面案例可供参考
一、数据绑定
1)在FrameworkElement类下有两个重要的属性。
- Resources:获取或设置本地定义的资源字典。
- DataContext:获取或设置元素参与数据绑定时的数据上下文。
利用这两个属性,可以实现UI数据直接与后台的类进行绑定
2)前端UI界面属性值等动态与后台绑定的方式有多种,此处列出后台设置DataContext以及前端设置DataContext的两种方式,以及数据双向绑定的最佳实践
前端设置DataContext
纯前端的方式好处在于,编译一下,就可以在设计阶段看到效果。
1)先定义好我们的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp2.entity
{
public class MyButtton
{
public string color {
get; set; } = "Red";
}
}
2)在前端按照步骤引入
<Window x:Class="WpfApp2.login"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
xmlns:btn="clr-namespace:WpfApp2.entity"
mc:Ignorable="d"
Title="登录页" Height="450" Width="800"
>
<Grid Name="g">
<!-- 1.声明资源位置 xmlns:btn="clr-namespace:WpfApp2.entity" -->
<!-- 2.绑定类资源,key是别名,value是类 -->
<Grid.Resources>
<btn:MyButtton x:Key="myDatasource"/>
</Grid.Resources>
<!-- 3.将绑定的资源加入到当前上下文(加入后即可使用) -->
<Grid.DataContext>
<Binding Source="{StaticResource myDatasource}"/>
</Grid.DataContext>
<!-- 4.使用属性,直接使用类的属性名即可 -->
<Button Background="{Binding Path=color}" Width="100" Height="50" Click="Button_Click_1">按钮</Button>
</Grid>
</Window>
后台设置DataContext
在设计阶段是看不到效果的,但是灵活性更高,属性值不用写死
1)定义一个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp2.entity
{
public class Mytitle
{
public