Add dependency property to existing .NET class

In a WPF project, I have a bunch of controls in which I would like to be able to set individual Margin properties and save other values. Therefore, I would like to avoid setting the full field to the new Thickness ( Margin="0,5,0,15" ). Since many fields are set from styles, etc. But in some cases, I would like to deviate from the general styles for certain controls.

I thought, why not register a couple of new dependency properties in the .NET FrameWorkElement class, as shown (for example, only MarginLeft is displayed):

 public class FrameWorkElementExtensions: FrameworkElement { public static readonly DependencyProperty MarginLeftProperty = DependencyProperty.Register("MarginLeft", typeof(Int16?), typeof(FrameworkElement), new PropertyMetadata(null, OnMarginLeftPropertyChanged)); public Int16? MarginLeft { get { return (Int16?)GetValue(MarginLeftProperty); } set { SetValue(MarginLeftProperty, value); } } private static void OnMarginLeftPropertyChanged(object obj, DependencyPropertyChangedEventArgs e) { if (obj != null && obj is UIElement) { FrameworkElement element = (FrameworkElement)obj; element.Margin = new Thickness((Int16?)e.NewValue ?? 0, element.Margin.Top, element.Margin.Right, element.Margin.Bottom); } } } 

But this property is not available in code or in XAML. I can figure it out somehow, because this dummy class is never created or not used at all. I tried to make it a static class, but then you cannot get the result from FrameWorkElement (which I need for the GetValue and SetValue methods).

I could not find any resource on the network that addresses a more general question: can you add dependency properties to exit .NET classes?

Any help / wise advice is appreciated.

BTW: also evaluating a solution to change only one field component (thickness);)

-1
source share
2 answers

If you want to define a property that should be set on an object that you are not, then you want to define an attached property, in which case you should use RegisterAttached instead of Register. You should also define the property as static get / set methods, and not as an instance property, as this will not be set in the instance of your object, but in some unknown framework element. The help example from the link shows an example. Links in other comments also contain more information and examples.

+4
source

If you want to change only one component of the usage field in xaml Margin = "1,2,3,4", where 1 is left, 2 is top, 3 is lowercase, 4 is lower

-2
source

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


All Articles