I didn't like how verbose dp's are, since most of the code is just repeated, I just wrapped it in a generic class.
Having seen quite allot of sample code, I was wondering why more people aren't doing the same.
I haven't come across any problems to speak of in my demo application, and it makes the ViewModels easier to manage.
Sample:
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;
}
Is this a bad idea?
It is not a bad idea, and well worth a try, but it will not work!
You have essentially defined a single dependency property named "Value". This will be OK if you only ever access it via your CLR wrapper (i.e. the get / set code for your Value property). However, much of the framework affects the dependency property directly. For example, style setters, animations will not be able to use your dependency property.
I too share your pain with the DP boilerplate code, which is why I came up with a declarative solution:
[DependencyPropertyDecl("Maximum", typeof(double), 0.0)]
[DependencyPropertyDecl("Minimum", typeof(double), 0.0)]
public partial class RangeControl : UserControl
{
...
}
The actual dependency properties are generated by a T4 template within Visual Studio.
https://blog.scottlogic.com/2009/08/18/declarative-dependency-property-definition-with-t4-dte.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With