WPF Label控件在数据绑定Content属性变化触发TargetUpdated事件简单实现类似TextChanged 事件效果

时间:2023-03-09 15:54:42
WPF Label控件在数据绑定Content属性变化触发TargetUpdated事件简单实现类似TextChanged 事件效果

原文:WPF Label控件在数据绑定Content属性变化触发TargetUpdated事件简单实现类似TextChanged 事件效果

 

本以为Label也有TextChanged
事件,但在使用的时候却没找到,网友说Label的Content属性改变肯定是使用赋值操作,赋值的时候就可以对其进行相应的操作所以不需TextChanged
事件。

上MSDN查了一下,TextChanged
事件在TextBoxBase类中;而Label和TextBox的继承关系如下:

Label:

System.Object

  System.Windows.Threading.DispatcherObject

    System.Windows.DependencyObject

      System.Windows.Media.Visual

        System.Windows.UIElement

          System.Windows.FrameworkElement

            System.Windows.Controls.Control

             System.Windows.Controls.ContentControl
                System.Windows.Controls.Label

 

TextBox:

System.Object

  System.Windows.Threading.DispatcherObject

    System.Windows.DependencyObject

      System.Windows.Media.Visual

        System.Windows.UIElement

          System.Windows.FrameworkElement

            System.Windows.Controls.Control

             System.Windows.Controls.Primitives.TextBoxBase
                System.Windows.Controls.TextBox
                  System.Windows.Controls.Primitives.DatePickerTextBox

                  System.Windows.Controls.Ribbon.RibbonTextBox

 

从上面红色就可以看出继承路径的不同,所以Label没有TextChanged
事件;

如何实现修改Label的Content属性自动执行类似TextChanged 事件呢?

这里实现了一种使用数据绑定的方式,借助TargetUpdated事件进行类似TextChanged
事件;

 

具体代码供参考:

项目中使用工厂模式设置好了数据绑定:

 if (element
is UIElement)

                        {

                            UIElement uiElement = element
as UIElement;

                            Binding binding =
new Binding();

                            binding.Mode =
BindingMode.TwoWay;

                            binding.Path = new PropertyPath(item.Value.DataPath);

                            binding.Source = item.Value.DataSource;

                            binding.NotifyOnTargetUpdated = true;

                            DependencyProperty dependProperty = GetDependencyProperty(item.Value.BindingProperty);

                            BindingOperations.SetBinding(uiElement, dependProperty, binding);

                        }

想使用TargetUpdated事件binding.NotifyOnTargetUpdated
属性必须为True;

然后为Label注册 TargetUpdated 事件:

label.TargetUpdated += Label_DataContextChanged;

 

 

至此就可以简单实现类似TextChanged
事件。

 

不对之处望指教!