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?