gpt4 book ai didi

c# - 为什么人们不将依赖属性包装在通用类中?

转载 作者:太空狗 更新时间:2023-10-29 20:01:58 25 4
gpt4 key购买 nike

我不喜欢 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;
}

这是个坏主意吗?

最佳答案

这个主意不错,值得一试,但行不通!

您实际上已经定义了一个名为“Value”的依赖属性。如果您只通过 CLR 包装器(即您的 Value 属性的获取/设置代码)访问它,这将是可以的。然而,许多框架直接影响依赖属性。例如,样式 setter 、动画将无法使用您的依赖属性。

我也分担了您对 DP 样板代码的痛苦,这就是我提出声明式解决方案的原因:

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

实际的依赖属性由 Visual Studio 中的 T4 模板生成。

https://blog.scottlogic.com/2009/08/18/declarative-dependency-property-definition-with-t4-dte.html

关于c# - 为什么人们不将依赖属性包装在通用类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4501525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com