Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Silverlight mobile: A simple workaround to the lack of a Command property on a button

4.90/5 (3 votes)
16 Aug 2010GPL3 12.1K  
A simple workaround to the lack of a Command property on a button

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:

C#
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:

XML
...
<Button Grid.Row="1" Content="Settings"
Attached:Attached.Command="{Binding Path=SettingsCommand}" />
...

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)