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);)