一個大佬做的本子網(wǎng)站專業(yè)seo站長工具
一、目的:開發(fā)過程中,經(jīng)常碰到使用別人的控件時有些屬性改變沒有對應(yīng)的事件拋出,從而無法做處理。比如TextBlock當(dāng)修改了IsEnabled屬性我們可以用IsEnabledChanged事件去做對應(yīng)的邏輯處理,那么如果有類似Background屬性改變我想找對應(yīng)的事件該如何處理,本文介紹DependencyPropertyDescriptor的應(yīng)用,用該類可以監(jiān)視到Background改變的處理
二、演示
可以看到,當(dāng)修改TextBlock的Background屬性時,Text的值也做出相應(yīng)改變。?
三、環(huán)境
VS2022
四、實現(xiàn)
相關(guān)代碼
定義一個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>
應(yīng)用?DependencyPropertyDescriptor注冊Textblock的Background改變時的響應(yīng)事件
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將想要監(jiān)視的Textblock注冊通知
? ? ? ? ? dependencyPropertyDescriptor.AddValueChanged(this.g_dpd, (s, e) =>
? ? ? ? ? {
? ? ? ? ? ? ? this.g_dpd.Text = this.g_dpd.Background.ToString();
? ? ? ? ? });
同理其他依賴屬性改變也可以用此方法處理,比如常見的ListBox的ItemsSource屬性改變沒有通知,我們就可以用此方法處理如果數(shù)據(jù)源改變了我們要做一些刷新處理。
五、需要了解的知識點
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個人主頁-嗶哩嗶哩視頻