[英]Custom Control: How to Call Method When Inherited Dependency Property Changes?
I'm writing a custom control that inherits ItemsControl. 我正在编写一个继承ItemsControl的自定义控件。 I need to call a method whenever certain properties change.
每当某些属性更改时,我需要调用一个方法。 For my own dependency properties I can call this in the setter no problem, but for inherited ones like ItemsSource I don't know how to do this and I'd like to learn how without overriding the whole thing.
对于我自己的依赖项属性,我可以在setter中将其称为没有问题,但是对于诸如ItemsSource之类的继承属性,我不知道如何执行此操作,并且我想学习如何在不覆盖整个内容的情况下进行操作。
When searching for this I saw mention that this could be done with OverrideMetadata in WPF at least (my project is UWP). 在搜索此内容时,我看到提到至少可以使用WPF中的OverrideMetadata来完成此操作(我的项目是UWP)。 I see how OverrideMetadata is used to change the default value, but I don't see how it can be used as a property changed notification.
我了解了如何使用OverrideMetadata更改默认值,但看不到如何将其用作属性更改通知。
There's a new method in UWP called RegisterPropertyChangedCallback
designed just for this. UWP中有一个专门为此设计的名为
RegisterPropertyChangedCallback
的新方法。 For example, the following is how I remove the default entrance transition in an extended GridView
control. 例如,以下是我如何在扩展的
GridView
控件中删除默认入口过渡的方法。
// Remove the default entrance transition if existed.
RegisterPropertyChangedCallback(ItemContainerTransitionsProperty, (s, e) =>
{
var entranceThemeTransition = ItemContainerTransitions.OfType<EntranceThemeTransition>().SingleOrDefault();
if (entranceThemeTransition != null)
{
ItemContainerTransitions.Remove(entranceThemeTransition);
}
})
You can un-register using UnregisterPropertyChangedCallback
. 您可以使用
UnregisterPropertyChangedCallback
。
For the ItemsSource
property you could just override the OnItemsSourceChanged
method but for any other dependency property you could use a DependencyPropertyDescriptor
: 对于
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)
{
//...
}
}
That goes for WPF. WPF就是这样。 In a UWP app you should be able to use @Thomas Levesque's
DependencyPropertyWatcher
class: https://www.thomaslevesque.com/2013/04/21/detecting-dependency-property-changes-in-winrt/ 在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.