[英]Custom Control: How to Call Method When Inherited Dependency Property Changes?
我正在編寫一個繼承ItemsControl的自定義控件。 每當某些屬性更改時,我需要調用一個方法。 對於我自己的依賴項屬性,我可以在setter中將其稱為沒有問題,但是對於諸如ItemsSource之類的繼承屬性,我不知道如何執行此操作,並且我想學習如何在不覆蓋整個內容的情況下進行操作。
在搜索此內容時,我看到提到至少可以使用WPF中的OverrideMetadata來完成此操作(我的項目是UWP)。 我了解了如何使用OverrideMetadata更改默認值,但看不到如何將其用作屬性更改通知。
UWP中有一個專門為此設計的名為RegisterPropertyChangedCallback
的新方法。 例如,以下是我如何在擴展的GridView
控件中刪除默認入口過渡的方法。
// Remove the default entrance transition if existed.
RegisterPropertyChangedCallback(ItemContainerTransitionsProperty, (s, e) =>
{
var entranceThemeTransition = ItemContainerTransitions.OfType<EntranceThemeTransition>().SingleOrDefault();
if (entranceThemeTransition != null)
{
ItemContainerTransitions.Remove(entranceThemeTransition);
}
})
您可以使用UnregisterPropertyChangedCallback
。
可以在此處找到更多信息。
對於ItemsSource
屬性,您可以僅重寫OnItemsSourceChanged
方法,但是對於任何其他依賴項屬性,可以使用DependencyPropertyDescriptor
:
public class MyItemsControl : ItemsControl
{
public MyItemsControl()
{
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor
.FromProperty(ItemsControl.ItemsSourceProperty, typeof(ItemsControl));
if (dpd != null)
{
dpd.AddValueChanged(this, OnMyItemsSourceChange);
}
}
private void OnMyItemsSourceChange(object sender, EventArgs e)
{
//...
}
}
WPF就是這樣。 在UWP應用中,您應該可以使用@Thomas Levesque的DependencyPropertyWatcher
類: https ://www.thomaslevesque.com/2013/04/21/detecting-dependency-property-changes-in-winrt/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.