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 方法被触发。``

  • 相关阅读:
    当tp5项目上传到服务器之后遇见的各种bug(不定期更新)
    解决LAMP下 服务器IP无法访问
    thinkphp5多图上传+同时删除本地文件
    from提交表单后 数据提交到后台 但不跳转页面 非ajax 用iframe
    window7 安装sass和compass
    开源操作系统课程设计
    Hadoop伪分布式搭建实验总结
    排序集合
    快排
    邻接矩阵
  • 原文地址:https://www.cnblogs.com/ganbei/p/15631361.html
Copyright © 2011-2022 走看看