WPF MVVM 模式如何监听IsVisibleChanged 事件

原本以为这是一个很简单的问题,但是我却走了不少的弯路。记录下来自省。

我使用的是库System.Windows.Interactivity.dll,首先在xaml 中使用了EventTrrigger

复制代码
<!--  当 IsVisibleChanged 事件触发时,执行绑定的命令  -->
<!--
            <i:EventTrigger EventName="IsVisibleChanged">
                <i:InvokeCommandAction Command="{Binding ElementName=MainGrid, Path=DataContext.IsVisibleChangedCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

但是发现是无效的。经过 改变IvokeCommandAction的参数,等方式,发现都无法触发。

最后决定使用behavior 来进行

接下来的写法如下

1、首先定义一个Behavior,

(注意:这里我也遇到了一个问题,原本我binding 的是Visibility 这个属性的,但是我也发现无法触发。通过测试发现,不是代码的问题。而是Visibility 从始至终都是Visibility.Visible ,但是IsVisible的属性,确实变化过的。这有点超乎我的认知。我认为这两个应该是同步的。所以最终attach 到IsVisible 的属性上)

复制代码
    public class VisibilityMonitorBehavior : Behavior<UserControl>
    {
        // 定义一个 DependencyProperty 用于绑定 Visibility 属性
        public static readonly DependencyProperty VisibilityProperty =
            DependencyProperty.Register(
                "IsVisible",
                typeof(bool),
                typeof(VisibilityMonitorBehavior),
                new PropertyMetadata(true, OnVisibilityChanged));

        private static void OnVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is VisibilityMonitorBehavior behavior && behavior.AssociatedObject != null)
            {
                var newVisibility = (bool)e.NewValue;
                if (newVisibility == true)
                {
                    (behavior.AssociatedObject.DataContext as UIViewModelBase).EnableTimer(true);
                }
                else
                {
                    (behavior.AssociatedObject.DataContext as UIViewModelBase).EnableTimer(false);
                }
                LOG.Info($"{behavior.AssociatedObject.Name}Visibility changed to: {newVisibility}");
            }
        }

        public bool IsVisible
        {
            get => (bool)GetValue(VisibilityProperty);
            set => SetValue(VisibilityProperty, value);
        }
        // 关联控件时初始化绑定
        protected override void OnAttached()
        {
            base.OnAttached();

            if (AssociatedObject != null)
            {
                // 绑定 AssociatedObject 的 Visibility 属性到行为的 VisibilityProperty
                var binding = new System.Windows.Data.Binding("IsVisible")
                {
                    Source = AssociatedObject,
                    Mode = System.Windows.Data.BindingMode.OneWay
                };
                BindingOperations.SetBinding(this, VisibilityProperty, binding);
            }
        }

        // 移除控件时清理资源
        protected override void OnDetaching()
        {
            BindingOperations.ClearBinding(this, VisibilityProperty);
            base.OnDetaching();
        }

    }

通过这种的方式,终于可以监听到IsVisibleChanged 事件了。

值得记录的是,我需要动态添加这个behavior ,因此把这部分代码也贴出来。以供后期查看。

其中control就是控件

复制代码
// 动态 添加 VisibilityMonitorBehavior
            var behaviors = Interaction.GetBehaviors(control);
            var visibilityBehavior = new VisibilityMonitorBehavior();
            behaviors.Add(visibilityBehavior);
相关推荐
绿龙术士1 天前
构建现代化WPF应用:数据驱动开发与高级特性解析
c#·wpf
wangnaisheng3 天前
【WPF】Opacity 属性的使用
wpf
姬激薄3 天前
配置Hadoop集群-集群配置
wpf
python算法(魔法师版)3 天前
.NET 在鸿蒙系统上的适配现状
华为od·华为·华为云·.net·wpf·harmonyos
大道随心3 天前
【wpf】11 在WPF中实现父窗口蒙版效果:原理详解与进阶优化
wpf
zizisuo4 天前
9.1.领域驱动设计
wpf
大道随心4 天前
【wpf】10 C#树形控件高效实现:递归构建与路径查找优化详解
开发语言·c#·wpf
离歌漠4 天前
WPF内嵌其他进程的窗口
c#·wpf
沉到海底去吧Go4 天前
【身份证识别表格】批量识别身份证扫描件或照片保存为Excel表格,怎么大批量将身份证图片转为excel表格?基于WPF和腾讯OCR的识别方案
ocr·wpf·excel·身份证识别表格·批量扫描件身份证转表格·图片识别表格·图片识别excel表格
csdn_aspnet5 天前
WPF 性能 UI 虚拟化 软件开发人员的思考
ui·wpf