I am trying to use the MVVM template in my Silverlight 3 application, and I am having problems binding a working view model to the command property. First, I'm trying to add an attached ClickCommand property, for example:
public static class Command { public static readonly DependencyProperty ClickCommandProperty = DependencyProperty.RegisterAttached( "ClickCommand", typeof(Command<RoutedEventHandler>), typeof(Command), null); public static Command<RoutedEventHandler> GetClickCommand( DependencyObject target) { return target.GetValue(ClickCommandProperty) as Command<RoutedEventHandler>; } public static void SetClickCommand( DependencyObject target, Command<RoutedEventHandler> value) {
The generic Command class is the wrapper around the delegate. I only wrap the delegate because I was wondering if I had a delegate type for the property, because initially I did not work for me. Here is this class:
public class Command<T> /* I'm not allowed to constrain T to a delegate type */ { public Command(T action) { this.Action = action; } public T Action { get; set; } }
This is how I use the attached property:
<Button u:Command.ClickCommand="{Binding DoThatThing}" Content="New"/>
The syntax seems acceptable, and I think that when I tested all of this with a string type of properties, it worked fine. Here's a view model class that is associated with:
public class MyViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate { }; public Command<RoutedEventHandler> DoThatThing { get { return new Command<RoutedEventHandler>( (s, e) => Debug.WriteLine("Never output!")); } } }
The delegate contained in the Command property is never called. Also, when I put breakpoints in the getter and setter of the attached property, they are never reached.
When I try to isolate the problem, I change the type of the property to a string; a breakpoint in the getter and setter also was not reached, but throwing an exception in them led to the termination of the application, so I consider it an eccentricity of the structure.
Why is this stuff not working? I also welcome alternative, hopefully simpler ways to bind event handlers to view models.