Introduction
Windows 8 Developer Preview and blend 5 Developer Preview Edtion does not supportEventtocommandBehaviour yet (Mvvm light ToolkitIs availableMetro: Http://mvvmlight.codeplex.com but blend behaviors not). and cannot developers want to implement the event to command in its mvvm pattern. So we need the attached command for Metro (similar withAttachedcommandIn WPF ).
Design the code
Well, let's start.
Usually, in mvvm pattern, we like to declare the value properties and the commands in the viewmodel, which use the databinding on The View. and that can do the "data drives UI" job. but let us check the metro style app. although it use the XAML, and winrt compoenets, it still can use mvvm pattern as its architecture. metro still supports databinding and yes we still can let "data" drive the "Metro UI ".
However, it is easy to implement the properties and commands in viewmodel, but not easy to assign one UI control event to one command. in WPF, We cocould use the blend SDK behaviour to assign one event to a command, or I usually recommend to design one attachedcommand, like this did: http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb. but just checking the mvvm light toolkit for Metro, it cannot provide the eventtocommand behaviour amd the blend 5 Developer Preview version does not provide the behaviour. so we just need to design one attachedcommand for Metro.
In out attachedcommand class, we shoshould declare TWO Attached properties, command and routedevent property.
/// <summary>
/// Command attached property
/// </summary>
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command",
"Object", // should be "Object" instead of "ICommand" interface, resolve the null reference exception
typeof(AttachedCommand).FullName, new PropertyMetadata(DependencyProperty.UnsetValue));
public static ICommand GetCommand(DependencyObject d)
{
return (ICommand)d.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject d, ICommand value)
{
d.SetValue(CommandProperty, value);
}
/// <summary>
/// RoutedEvent property
/// </summary>
public static readonly DependencyProperty RoutedEventProperty =
DependencyProperty.RegisterAttached("RoutedEvent",
"String",
typeof(AttachedCommand).FullName,
new PropertyMetadata(String.Empty, new PropertyChangedCallback(OnRoutedEventChanged)));
public static String GetRoutedEvent(DependencyObject d)
{
return (String)d.GetValue(RoutedEventProperty);
}
public static void SetRoutedEvent(DependencyObject d, String value)
{
d.SetValue(RoutedEventProperty, value);
}
We shocould register the attached property in Metro via the string of the type (similar with the Silverlight solution), and for interface, we shocould use "object" instead. and not sure if it will be resolved in next Windows 8 version, but for interface, it will throw the nullreferenceexception.
Below is the property changed callback for routedevent property:
private static void OnRoutedEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
String routedEvent = (String)e.NewValue;
if (!String.IsNullOrEmpty(routedEvent))
{
EventHooker eventHooker = new EventHooker();
eventHooker.AttachedCommandObject = d;
EventInfo eventInfo = GetEventInfo(d.GetType(), routedEvent);
if (eventInfo != null)
{
eventInfo.AddEventHandler(d, eventHooker.GetEventHandler(eventInfo));
}
}
}
We need the eventinfo by reflecting the metro dependecyobject. but in Metro, the reflection just can list the members which are declared in the current type directly. it cannot list all members inherits from the base type. so we shoshould use one method to search the event member from its base types:
/// <summary>
/// Search the EventInfo from the type and its base types
/// </summary>
/// <param name="type"></param>
/// <param name="eventName"></param>
/// <returns></returns> <returns />
private static EventInfo GetEventInfo(Type type, string eventName)
{
EventInfo eventInfo = null;
eventInfo = type.GetTypeInfo().GetDeclaredEvent(eventName);
if (eventInfo == null)
{
Type baseType = type.GetTypeInfo().BaseType;
if (baseType != null)
return GetEventInfo(type.GetTypeInfo().BaseType, eventName);
else
return eventInfo;
}
return eventInfo;
}
When the specific event is fired on the control, we shocould return the event handler. So there is an eventhooker that can return one "oneventraised" method, and execute the command in it:
internal sealed class EventHooker
{
public DependencyObject AttachedCommandObject { get; set; }
public Delegate GetEventHandler(EventInfo eventInfo)
{
Delegate del = null;
if (eventInfo == null)
throw new ArgumentNullException("eventInfo");
if (eventInfo.EventHandlerType == null)
throw new ArgumentNullException("eventInfo.EventHandlerType");
if (del == null)
del = this.GetType().GetTypeInfo().GetDeclaredMethod("OnEventRaised").CreateDelegate(eventInfo.EventHandlerType, this);
return del;
}
private void OnEventRaised(object sender, object e) // the second parameter in Windows.UI.Xaml.EventHandler is Object
{
ICommand command = (ICommand)(sender as DependencyObject).GetValue(AttachedCommand.CommandProperty);
if (command != null)
command.Execute(null);
}
}
How to Use
We shoshould add one delegatecommand or relaycommand (icommand) for Metro, which can help us to return the icommand in the viewmodel. and we cocould bind this icommand property on the attachedcommand. command property. below is one delegatecommand for Metro. and mvvm light toolkit provides the relaycommand available for metro also.
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event Windows.UI.Xaml.EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
return true;
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, null);
}
}
}
Please note, winrt eventhandler is different with the system. eventhandler. And windows. UI. XAML. eventhandler has two object parameters, the second one is not eventargs.
Then in the view, we just cocould set the attachedcommand in any controls in Metro:
<Button Content="Test Button"
local:AttachedCommand.RoutedEvent="PointerEntered" local:AttachedCommand.Command="{Binding TestCommand}"/>
References
- Http://marlongrech.wordpress.com/2008/12/04/attachedcommandbehavior-aka-acb/
- Http://sachabarber.net /? P = 514
- Http://social.msdn.microsoft.com/Forums/en-us/winappswithcsharp/thread/b4a1d607-9cd4-4472-b5c1-fe41167d9ea5