zoukankan      html  css  js  c++  java
  • [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 方法被触发。``

  • 相关阅读:
    负载均衡--hash slot算法
    redis cluster slots数量 为何是16384(2的14次方)
    ZooKeeper原理与它的集群工作流程
    5分钟入门chrony
    微服务的下一步,离不开服务网格
    sar统计日流量与实时流量
    docker查看jvm内存占用
    k8s编排
    Rsync 排除文件
    Kubernetes 中优雅停机和零宕机部署
  • 原文地址:https://www.cnblogs.com/ganbei/p/15631361.html
Copyright © 2011-2022 走看看