按照Vue写WPF(1):属性绑定

前言

作为一个使用Vue非常熟练的C#全干工程师。当我在接触WPF的时候,我就一直想用Vue的想法去重写WPF框架。经过一个星期的琢磨,终于琢磨出来了如何优雅的入参。期间看了上百篇博客,浏览了一堆的视频教程。

代码

用户控件的cs
TestController.xaml

 public partial class TestControl : UserControl
    {
        /// <summary>
        /// 声明数据源
        /// </summary>
        public  TestControllerViewModel testControl = new TestControllerViewModel();


        /// <summary>
        /// 用于静态编译通过,根据我两天的试验,这个值是不会触发get和set指令的,就是个花瓶。
        /// </summary>
        public string TestTitle { get; set; }


        /// <summary>
        /// 用于声明依赖属性,不让只让直接传值,不让Bind传值
        /// </summary>
        public static readonly DependencyProperty TestTitleProperty =
        DependencyProperty.Register("TestTitle", typeof(string), typeof(TestControl), new PropertyMetadata("TestTitle",new PropertyChangedCallback((item,res) =>
        {
            //使用回调函数去重新设置数据源
            var model = (TestControl)item;
            model.testControl.TestTitle = res.NewValue as string;
        })));



        public TestControl()
        {

            InitializeComponent();
            //必须要这么写,不然Bind赋值传不进去
            ( this.Content as FrameworkElement ).DataContext = testControl;
        }
    }

TestController.xaml.cs
用户控件的xaml

<Grid Background="White">
    <StackPanel>
        <TextBlock Text="{Binding TestTitle}" FontSize="50"/>
        <!--<Button Content="按钮" FontSize="50" />-->
    </StackPanel>
</Grid>

TestControllerViewModel,数据源

 public class TestControllerViewModel
    {
        public string TestTitle { get; set; }

        

        public TestControllerViewModel()
        {
            TestTitle = "我是初始值";
        }
    }

主窗口

<Grid>
        <StackPanel>
            <!--这里面传的是"我是Bind赋值"-->
            <Views:TestControl TestTitle="{Binding TestTitle}" />
            <Views:TestControl TestTitle="我是直接赋值" />
            <Views:TestControl />
        </StackPanel>
    </Grid>

实现效果

在这里插入图片描述

代码逻辑

在这里插入图片描述

总结

期间遇到许多困难,WPF国内相关资料极少,英语也不知道怎么提问,GPT也没有给我想要的答案,难得我都要放弃了。因为我一直想像Vue那样优雅的入参,按照Vue的一切都是组件的想法去开发,因为这样极大的减少了开发的难度,降低了耦合,提高了组件的复用。

幸好我成功了,所有的努力没有白费。只要我能Bind入参,我就能按照Vue的逻辑重构WPF页面的开发。我相信我有这个能力。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值