【问题标题】:AutomationID attached property changedAutomationID 附加属性已更改
【发布时间】:2021-08-09 17:22:54
【问题描述】:

我有一个 wpf 应用程序, OnLoaded 事件我将一个automationId 附加到我的FrameworkElement(元素):
element.SetValue(AutomationProperties.AutomationIdProperty, path); 

但是这个automationId在代码的某个地方被修改了。 我想添加一个侦听器或可以帮助我调试的东西。 我正在等待类似的东西

AutomationProperties.AutomationIdProperty+= AutomationIdChanged; 
private void AutomationIdChanged(object sender, EventArgs e)
       {
         var oldVal =   e.oldValue ;
         var newVal=   e.NewValue;
       }

【问题讨论】:

    标签: c# wpf frameworkelement


    【解决方案1】:

    重要提示:您没有提到目标框架。我的答案基于 .NET Framework 4.6.2。

    您可以使用DependencyPropertyDescriptor 并致电AddValueChanged 来监听更改。不幸的是,这个回调函数不提供旧值。不过,我会提供一种解决方法。

    我想通过一个扩展方法来解决它,命名为DebugAutomationIdChanged:

    public static class FrameworkElementExt
    {
        private static readonly ConditionalWeakTable<FrameworkElement, string> AutomationIdCwt =
            new ConditionalWeakTable<FrameworkElement, string>();
    
        public static void DebugAutomationIdChanged(this FrameworkElement element)
        {
            var descriptor = DependencyPropertyDescriptor.FromProperty(
                AutomationProperties.AutomationIdProperty,
                element.GetType()
            );
    
            descriptor.AddValueChanged(element, delegate
            {
                var currentValue = AutomationProperties.GetAutomationId(element);
                if (AutomationIdCwt.TryGetValue(element, out var oldValue))
                {
                    Debug.WriteLine($"AutomationId changed: '{oldValue}' -> '{currentValue}'");
                    AutomationIdCwt.Remove(element);
                }
                else
                {
                    Debug.WriteLine($"AutomationId changed: '{currentValue}'");
                }
    
                AutomationIdCwt.Add(element, currentValue);
            });
        }
    }
    

    稍后,在您的代码中,您可以这样调用它(为了简单起见,删除了一些代码):

    ...
    element.DebugAutomationIdChanged();
    element.SetValue(AutomationProperties.AutomationIdProperty, "fe-01");
    ...
    

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 2014-12-17
      • 2020-05-04
      • 1970-01-01
      相关资源
      最近更新 更多