且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-08-12 18:00:41

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

 

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

MSDN查了一下,TextChanged 事件TextBoxBase类中;而LabelTextBox的继承关系如下:

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 事件

如何实现修改LabelContent属性自动执行类似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 事件

 

不对之处望指教!