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

作者:ganbei

出处:https://www.cnblogs.com/ganbei/p/15631361.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   干杯Archer  阅读(591)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up light_mode palette
选择主题