Reputation: 107
I'm learning to develop custom controls for UWP and I have to develop a control that contains a ScrollViewer. The generic.xaml looks like this:
<Style TargetType="local:TemplatedScroller" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TemplatedScroller">
<ScrollViewer x:Name="NumberScroller"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The corresponding cs class is pretty simple right now.
public sealed class TemplatedScroller : Control
{
public TemplatedScroller()
{
this.DefaultStyleKey = typeof(TemplatedScroller);
}
private ScrollViewer numberScroller;
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
numberScroller = GetTemplateChild("NumberScroller") as ScrollViewer;
}
}
In my control I have to know when the user will scroll the content so I thought that I can register a property changed callback for scroller's VerticalOffset property using RegisterPropertyChangedCallback. I can register the callback in OnApplyTemplate method.
My question is where should I call the corresponding UnregisterPropertyChangedCallback? I could not find any Unload method (or similar) to override. Or is my approach wrong and this is not the way to do things in UWP?
Upvotes: 0
Views: 462
Reputation: 169200
My question is where should I call the corresponding UnregisterPropertyChangedCallback?
You don't unregister from a PropertyChangedCallback
of a dependency property.
There are two main reasons why you may want to unsubscribe from an event in the first place. Either you are no longer interested in receiving the information that the event publishes or you want to avoid having a memory leak.
Neither of these conditions apply here since the lifetime of the control is equal to the lifetime of the ScrollViewer
element in its ControlTemplate
and both the ScrollViewer
element and the dependency property are part of the control itself.
You may only leak memory if the lifetime of the subscriber and the publisher of an event differs:
Why and How to avoid Event Handler memory leaks?
So don't worry about unregister from the PropertyChangedCallback
.
The best place would otherwise probably be when the Unloaded event for the control occurs.
Upvotes: 2