Add Dependency Property to existing .NET class

本秂侑毒 提交于 2019-12-13 09:36:52

问题


IN a WPF project I have a bunch of controls in which I would like to be able to set individual Margin properties and conserve the other values. So, I would like to avoid setting the complete margin to a new Thickness (Margin="0,5,0,15"). Because many margin's are set from styles etc. But in individual cases I would like to deviate from the generic styles for certain controls.

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

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 doesn't come available in code-behind or in XAML. I can understand it somehow, because this dummy class is never instantiated or whatsoever. Tried to make it a static class but then you can't derive from FrameWorkElement (which I need for the GetValue and SetValue methods).

I couldn't find any resource on the net that treats the more generic question: Can you add dependency properties to exiting .NET classes?

Any help / wise advice is appreciated.

BTW: a solution for changing only one component of a Margin (Thickness) is also appreciated ;)


回答1:


If you want to define a property to be set on an object that you do not own then you want to define an attached property in which case you would use the RegisterAttached method instead of Register. Also you would define the property as static get/set methods and not as an instance property since this would not be set on an instance of your object but on some unknown frameworkelement. The help topic from the link shows an example. The links in the other comments also provide more information and examples.




回答2:


If you want change only one component of a margin use in xaml Margin="1,2,3,4", where 1 - left, 2 - top, 3 - rigth, 4 - bottom



来源:https://stackoverflow.com/questions/14318707/add-dependency-property-to-existing-net-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!