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

来源:互联网 发布:悟空传百年孤寂知乎 编辑:程序博客网 时间:2024/06/15 16:07

 

本以为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 = elementas 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 事件

 

不对之处望指教!

阅读全文
1 0
原创粉丝点击