为什么人们不将DependencyProperties包装在泛型类中?

时间:2010-12-21 16:31:04

标签: c# wpf generics dependency-properties

我不喜欢详细的dp,因为大多数代码都是重复的,我只是把它包装在一个泛型类中。

看过很多样本代码之后,我想知道为什么更多的人不会这样做。

我在演示应用程序中没有遇到任何问题,它使ViewModel更易于管理。

样品:

class GenericDependancyProperty<T> : DependencyObject
{
    // Value dependency property
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register( "Value", typeof( T ), typeof( GenericDependancyProperty ),
            new FrameworkPropertyMetadata( (T)default(T),
                new PropertyChangedCallback( OnValueChanged ) ) );

    // getter/setter for the Value dependancy property
    public T Value
    {
        get { return (T)GetValue( ValueProperty ); }
        set { SetValue( ValueProperty, value ); }
    }

    // Handles changes to the Value property.       
    private static void OnValueChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
        GenericDependancyProperty<T> target = (GenericDependancyProperty<T>)d;
        T oldValue = (T)e.OldValue;
        T newValue = target.Value;
        target.OnValueChanged( oldValue, newValue );
    }

    // Provides derived classes an opportunity to handle changes to the Value property. 
    protected virtual void OnValueChanged( T oldValue, T newValue )
    {
        if ( ValueChanged != null )
        {
            ValueChanged( newValue );
        }
    }

    // Value changed event
    public event Action<T> ValueChanged;
}

这是个坏主意吗?

4 个答案:

答案 0 :(得分:13)

这不是一个坏主意,值得一试,但它不会起作用!

你基本上定义了一个名为“Value”的依赖属性,如果你只是通过你的CLR包装器(即你的Value属性的get / set代码)来访问它,那就没问题,但是,很多框架直接影响依赖属性。例如,样式设置器,动画将无法使用您的依赖项属性。

我也用DP锅炉板代码分享你的痛苦,这就是我想出一个声明性解决方案的原因:

[DependencyPropertyDecl("Maximum", typeof(double), 0.0)]
[DependencyPropertyDecl("Minimum", typeof(double), 0.0)]
public partial class RangeControl : UserControl
{
    ...
}

实际依赖项属性由visual studio中的T4模板生成。

http://www.scottlogic.co.uk/blog/colin/2009/08/declarative-dependency-property-definition-with-t4-dte/

Colin E。

答案 1 :(得分:1)

我认为要指出的主要事情是你似乎是为了让你的视图模型类更整洁,但实际上没有任何理由在视图模型中使用依赖属性。

正如Colin的回答所示,在派生/用户控件中声明依赖项属性是最常见的。视图模型通常包含标准属性并实现INotifyPropertyChanged

此外,将依赖项属性放在派生控件类本身而不是单独的泛型/静态类中是有意义的,因为您需要静态引用它: MySlider.SpecialOpacityProperty。如果你在一个类中有这些东西,那么你就不能拥有2个具有相同名称的属性(对于不同的控件),或者如果使用泛型类,则无法在XAML中引用它。

答案 2 :(得分:0)

由于ValueProperty是静态的,无论您如何实例化类,该值都不会更改。我不明白这是怎么回事。

答案 3 :(得分:0)

您的解决方案不可行,灵活且根本无法扩展。

由于C#只允许使用单个基类,因此每个类可以同时拥有一个DP

这就是为什么它不起作用。

使用snippetscode generation作为Colin时,您应该采取哪些措施来缓解您的痛苦。

请记住,我们都有同样的痛苦。