So following on from my post on “Silverlight Mobile: A Simple workaround to the lack of a Data Type property on the DataTemplate
type”, I thought I would post my solution to the lack of a command property. It's yet another attached behaviour but I’m sure there will be pitfalls with this one and so this will hopefully be the start of a good discussion.
The Problem
So Silverlight mobile and MVVM are not exactly getting along like a house on fire at the moment. My second hurdle was avoiding click handlers in my code behind so I came up with an attached behaviour for a button. This will probably be re-factored to be more abstract or more likely strategized so that it can apply to more control types but I have no need for that at the moment. If I do end up strategising it, I will be sure to post it.
The Solution
So here’s the attached property:
public class Attached : Button
{
public static read-only DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(Button),
new PropertyMetadata(OnPropertyChanged));
private static void OnPropertyChanged(object sender,
DependencyPropertyChangedEventArgs args)
{
var obj = sender as Button;
obj.Click += new RoutedEventHandler((a, b) =>
{
var command = args.NewValue as ICommand;
if (command != null)
{
command.Execute(null);
}
});
}
private static RoutedEventHandler Clicked()
{
throw new NotImplementedException();
}
public static void SetCommand(
DependencyObject obj, string tabStop)
{
obj.SetValue(CommandProperty, tabStop);
}
public static object GetCommand(DependencyObject obj)
{
return (object)obj.GetValue(CommandProperty);
}
}
And the usage:
...
<Button Grid.Row="1" Content="Settings"
Attached:Attached.Command="{Binding Path=SettingsCommand}" />
...