一、目的:开发过程中,经常碰到使用别人的控件时有些属性改变没有对应的事件抛出,从而无法做处理。比如TextBlock当修改了IsEnabled属性我们可以用IsEnabledChanged事件去做对应的逻辑处理,那么如果有类似Background属性改变我想找对应的事件该如何处理,本文介绍DependencyPropertyDescriptor的应用,用该类可以监视到Background改变的处理
 二、演示
 

可以看到,当修改TextBlock的Background属性时,Text的值也做出相应改变。
三、环境
 VS2022
四、实现
相关代码
定义一个ComboBox去修改Textblock的Backround属性
            <DockPanel>
                <ComboBox x:Name="cbb_dpd" DockPanel.Dock="Top">
                    <SolidColorBrush Color="Yellow"/>
                    <SolidColorBrush Color="Orange"/>
                    <SolidColorBrush Color="Purple"/>
                    <SolidColorBrush Color="Green"/>
                </ComboBox>
                <TextBlock x:Name="g_dpd" 
                           TextAlignment="Center" 
                           FontSize="100" 
                           VerticalAlignment="Stretch" 
                           Background="{Binding ElementName=cbb_dpd,Path=SelectedItem}"/>
            </DockPanel>应用 DependencyPropertyDescriptor注册Textblock的Background改变时的响应事件
      public MainWindow()
      {
          InitializeComponent();
          var dependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(TextBlock.BackgroundProperty, typeof(TextBlock));
          dependencyPropertyDescriptor.AddValueChanged(this.g_dpd, (s, e) =>
          {
              this.g_dpd.Text = this.g_dpd.Background.ToString();
          });
      }核心代码是
首先,用一个依赖属性定义一个DependencyPropertyDescriptor
var dependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(TextBlock.BackgroundProperty, typeof(TextBlock));
之后,用DependencyPropertyDescriptor将想要监视的Textblock注册通知
          dependencyPropertyDescriptor.AddValueChanged(this.g_dpd, (s, e) =>
           {
               this.g_dpd.Text = this.g_dpd.Background.ToString();
           });
同理其他依赖属性改变也可以用此方法处理,比如常见的ListBox的ItemsSource属性改变没有通知,我们就可以用此方法处理如果数据源改变了我们要做一些刷新处理。
五、需要了解的知识点
DependencyPropertyDescriptor 类 (System.ComponentModel) | Microsoft Learn
PropertyDescriptor 类 (System.ComponentModel) | Microsoft Learn
DependencyProperty Class (System.Windows) | Microsoft Learn
TextBlock 类 (System.Windows.Controls) | Microsoft Learn
TextBlock.Background 属性 (System.Windows.Controls) | Microsoft Learn
六、源码地址
GitHub - HeBianGu/WPF-ControlDemo: 示例
GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库
GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库
七、了解更多
System.Windows.Controls 命名空间 | Microsoft Learn
https://github.com/HeBianGu
HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频



















