How to override dependency properties in a common class?

So I have a class; allows you to use the ScrollViewer class as an example. It has a dependency property called Content that accepts something like System.Object , great!

Let's say I derived a class from ScrollViewer , let's call it ZoomScrollViewer , it adds some basic zooming and panning with the mouse with a click on the keyboard. It also adds its own dependency property, AutoscaleContent .

Now I want to place ZoomScrollViewer in the user interface window, but I only want it to accept the Canvas as content. Naturally, I'm going to create a ZoomScrollViewer<T> class.

However, how do I change the Content property so that it accepts only elements of type <T> ? Can I override a dependency property? I was a little embarrassed and tried:

  public new T Content { get { return (T)base.Content; } set { base.Content = value; } } 

But of course, this is no longer a dependency property, so all XAML code fails when I set the bindings.

Edit: It should also be noted that I took a look at using:

 ZoomScrollViewer.ContentProperty.OverrideMetadata(typeof(ZoomScrollControl2<T>), new PropertyMetadata(...?)); 

To find out if I can do anything with this, but it seems that you can override the default only if I am missing something?

Update: now I tried to use the following:

 public class ZoomScrollControl2<T> : ZoomScrollViewer where T : FrameworkElement { static ZoomScrollControl2() { ContentProperty.OverrideMetadata(typeof(ZoomScrollControl2<T>), new FrameworkPropertyMetadata(typeof(ZoomScrollControl2<T>))); } } public class CanvasZoomControl : ZoomScrollControl2<Canvas> { } 

I thought this would work, but it seems to be consistent with any type of Content anyway.

Update: In short, I'm not sure that what I want to do is even possible, so I marked the discussion as an answer, although it is not an answer.

+4
source share
1 answer

I suggest trying this approach suggested by this MSDN article.

It must override the referral type, so you can refer to it using a derived type.

Dependency Property not created in the .NET Framework for derived types, since the search property to the right of the type tree has a cost in terms of performance, and given that we use DP to bind the UI, it can lead to undesirable performance problems.

+2
source

Source: https://habr.com/ru/post/1394378/


All Articles