ReSharper C# Live Template for Read-Only Dependency Property and Routed Event Boilerplate
Posted
by Bart Read
on Simple Talk
See other posts from Simple Talk
or by Bart Read
Published on Tue, 30 Nov 2010 12:28:00 GMT
Indexed on
2010/12/06
16:58 UTC
Read the original article
Hit count: 323
.NET
Following on from my previous post, where I shared a Live Template for quickly declaring a normal read-write dependency property and its associated property change event boilerplate, here's an unsurprisingly similar template for creating a read-only dependency property.
#region $PROPNAME$ Read-Only Property and Property Change Routed Event
private static readonly DependencyPropertyKey $PROPNAME$PropertyKey =
DependencyProperty.RegisterReadOnly(
"$PROPNAME$", typeof ( $PROPTYPE$ ), typeof ( $DECLARING_TYPE$ ),
new PropertyMetadata( $DEF_VALUE$ , On$PROPNAME$Changed ) );
public static readonly DependencyProperty $PROPNAME$Property =
$PROPNAME$PropertyKey.DependencyProperty;
public $PROPTYPE$ $PROPNAME$
{
get { return ( $PROPTYPE$ ) GetValue( $PROPNAME$Property ); }
private set { SetValue( $PROPNAME$PropertyKey, value ); }
}
public static readonly RoutedEvent $PROPNAME$ChangedEvent =
EventManager.RegisterRoutedEvent(
"$PROPNAME$Changed",
RoutingStrategy.$ROUTINGSTRATEGY$,
typeof( RoutedPropertyChangedEventHandler< $PROPTYPE$ > ),
typeof( $DECLARING_TYPE$ ) );
public event RoutedPropertyChangedEventHandler< $PROPTYPE$ > $PROPNAME$Changed
{
add { AddHandler( $PROPNAME$ChangedEvent, value ); }
remove { RemoveHandler( $PROPNAME$ChangedEvent, value ); }
}
private static void On$PROPNAME$Changed(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var $DECLARING_TYPE_var$ = d as $DECLARING_TYPE$;
var args = new RoutedPropertyChangedEventArgs< $PROPTYPE$ >(
( $PROPTYPE$ ) e.OldValue,
( $PROPTYPE$ ) e.NewValue );
args.RoutedEvent = $DECLARING_TYPE$.$PROPNAME$ChangedEvent;
$DECLARING_TYPE_var$.RaiseEvent( args );$END$
}
#endregion
The only real difference here is the addition of the DependencyPropertyKey, which allows your implementation to set the value of the dependency property without exposing the setter code to consumers of your type.
You'll probably find that you create read-only dependency properties much less often than read-write properties, but this should still save you some typing when you do need to do so.
© Simple Talk or respective owner