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

posted @ 2021-12-01 23:42  干杯Archer  阅读(483)  评论(0编辑  收藏  举报