当前位置: 代码网 > it编程>编程语言>C# > C# wpf定义ViewModelBase进行简化属性绑定

C# wpf定义ViewModelBase进行简化属性绑定

2024年05月26日 C# 我要评论
概述绑定机制是wpf的核心,也是界面独立的根本,尤其是使用了mvvm模式,没有业务逻辑的干扰,使得界面得以专注于绚丽效果的实现。在xaml中编写绑定语句后,在业务逻辑层需要定义相应的属性与其绑定,需要

概述

绑定机制是wpf的核心,也是界面独立的根本,尤其是使用了mvvm模式,没有业务逻辑的干扰,使得界面得以专注于绚丽效果的实现。在xaml中编写绑定语句后,在业务逻辑层需要定义相应的属性与其绑定,需要继承inotifypropertychanged,并通过propertychanged通知属性改变。但是每个地方都去继承实现inotifypropertychanged还是有点麻烦。

具体方法

1、继承inotifypropertychanged

继承inotifypropertychanged后需要定义一个事件。

public event propertychangedeventhandler propertychanged;

2、定义通知方法

定义一个动作属性改变的方法。这一步骤将2个参数,简化成了一个字符串参数。

  protected void raisepropertychangedevent( string propertyname )
        {     
            if (propertychanged != null)
            {
                propertychanged(this, new propertychangedeventargs(propertyname));
            }
        }

3、自动获取属性名

调用的时候要写属性名还是有点麻烦,进一步简化,将属性名参数省去。

在.net 4.5以下需要通过栈帧和反射获取属性名,在.net4.5或core1.0以上使用system.runtime.compilerservices.callermembername属性即可。

 string getcallermembername()
        {
            stacktrace trace = new stacktrace();
            stackframe frame = trace.getframe(2);//1代表上级,2代表上上级,以此类推  
            var propertyname = frame.getmethod().name;
            if (propertyname.startswith("get_") || propertyname.startswith("set_") || propertyname.startswith("put_"))
            {
                propertyname = propertyname.substring("get_".length);
            }
            return propertyname;
        }

通知方法作相应的修改如下。

        protected void raisepropertychangedevent(/*此属性在.net 4.5以下不支持将其注释即可*/[system.runtime.compilerservices.callermembername]  string propertyname = "")
        {           
            if (propertyname == "")
            {
                propertyname = getcallermembername();
            }
            if (propertychanged != null)
            {
                propertychanged(this, new propertychangedeventargs(propertyname));
            }
        }

注:在.net4.5以下只能调用getcallermembername,使用者觉得影响性能则直接使用参数赋值即可。

完整代码

    public abstract class viewmodelbase : inotifypropertychanged
    {
        public event propertychangedeventhandler propertychanged;
        protected void raisepropertychangedevent([system.runtime.compilerservices.callermembername] string propertyname = "")
        {
            if (propertyname == "")
            {
                propertyname = getcallermembername();
            }
            if (propertychanged != null)
            {
                propertychanged(this, new propertychangedeventargs(propertyname));
            }
        }
        string getcallermembername()
        {
            stacktrace trace = new stacktrace();
            stackframe frame = trace.getframe(2);//1代表上级,2代表上上级,以此类推  
            var propertyname = frame.getmethod().name;
            if (propertyname.startswith("get_") || propertyname.startswith("set_") || propertyname.startswith("put_"))
            {
                propertyname = propertyname.substring("get_".length);
            }
            return propertyname;
        }
    }

使用示例

timetick .cs

    public class timetick : viewmodelbase
    {
        public double seconds
        {
            set { _seconds = value; raisepropertychangedevent(); }
            get { return _seconds; }
        }
        double _seconds;
        public timetick()
        {
            dispatchertimer time = new dispatchertimer();
            time.tick += time_tick;       
            time.interval = timespan.frommilliseconds(1000);
            time.start();
        }
        private void time_tick(object sender, eventargs e)
        {
           //修改属性的值
            seconds++;
        }
    }

mainwindow.xaml.cs

 public mainwindow()
        {
            initializecomponent();
            this.datacontext = new timetick();
        }

mainwindow.xaml

<window x:class="wpfapp1.mainwindow"
        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:sys="clr-namespace:system;assembly=mscorlib"
        xmlns:local="clr-namespace:wpfapp1"     
        mc:ignorable="d"
        title="mainwindow" height="360" width="640">
    <grid  >
        <textblock  horizontalalignment="center" verticalalignment="center" text="{binding seconds}" fontsize="128"  foreground="#999999" loaded="textblock_loaded" ></textblock>
    </grid>
</window>

显示效果

到此这篇关于c# wpf定义viewmodelbase进行简化属性绑定的文章就介绍到这了,更多相关wpf viewmodelbase简化属性绑定内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com