• [WPF] 附加属性、行为(Behavior)触发方法(上)


    在ViewModel中,我们无法在构造函数中调用async 和 await ,我们可以用一个附加属性来做。

    我们实现的功能是要在view加载的时候触发一个Load() 方法。

    我们先创建一个静态类

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    
    namespace MyToDo.Common.Behivors
    {
        public static class LoadInstanceBehavior
        {
    
    
            public static string GetLoadInstance(DependencyObject obj)
            {
                return (string)obj.GetValue(LoadInstanceProperty);
            }
    
            public static void SetLoadInstance(DependencyObject obj, string value)
            {
                obj.SetValue(LoadInstanceProperty, value);
            }
    
            // Using a DependencyProperty as the backing store for LoadInstance.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty LoadInstanceProperty =
                DependencyProperty.RegisterAttached("LoadInstance", typeof(string), typeof(LoadInstanceBehavior), new PropertyMetadata(null, OnLoadInstanceChanged));
    
            private static void OnLoadInstanceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                //获取到触发这个事件的元素
                FrameworkElement element = d as FrameworkElement;
                if (element != null)
                {
                    element.Loaded += (s, e2) =>
                    {
                        //获取元素的DataContext
                        var viewmodel = element.DataContext;
                        if (viewmodel == null) return;
                        //利用反射来触发方法
                        var methodInfo = viewmodel.GetType().GetMethod(e.NewValue.ToString());
                        if (methodInfo != null) methodInfo.Invoke(viewmodel, null);
                    };
                }
    
            }
        }
    }
    
    

    上面的类相当于一个扩展方法

    我们将其应用于Xaml界面上,看看如何调用

    <!--在xaml中我们引用一下namespace-->
    xmlns:load="clr-namespace:MyToDo.Common.Behivors"
    <!--然后在窗口的xaml代码中使用这个方法-->
    load:LoadInstanceBehavior.LoadInstance="Load"
    <!--此处的Load 就是我们要触发的方法-->
    
    

    然后在View绑定的 ViewModel 中我们 来实现这个Load() 方法

     /// <summary>
            /// 加载数据 此处用的是 附加属性 触发
            /// </summary>
            public async void Load()
            {
                await _repository.GetDataAsync();
            }
    

    运行程序,就可以看到Load 方法被触发。``

  • 相关阅读:
    Qt图像处理技术六:拉普拉斯锐化
    linux下使用动态壁纸
    qt获得当前窗口所在屏幕的大小
    linux下动态壁纸(ubuntu20.04测试)
    使用qt+网上的api做股票查看器
    在deepin环境下安装qt开发环境和dtk开发环境
    Qt图像处理技术七:轮廓提取
    Qt图像处理技术五:图像的翻转(横向,竖向)
    基于平台开发人事档案管理功能
    让VS.Net根据表结构自动生成界面和C#代码
  • 原文地址:https://www.cnblogs.com/ganbei/p/15631361.html
Copyright © 2020-2023  润新知