《WPF》--DataContext数据双向绑定


提示:以下是本篇文章正文内容,下面案例可供参考

一、数据绑定

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 
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值