下面是一个如何使用 MenuFlyOutItem 实现命令绑定的示例。此实现利用了 Expression Blend 2013 中的行为。
XAML:
<HyperlinkButton
Content="{Binding SelectedItem.Name, ElementName=ContactList, Mode=OneWay}">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Holding">
<behaviors:MoveContactBehavior />
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem Text="Family" Command="{Binding MoveCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Text}" />
<MenuFlyoutItem Text="Friends" Command="{Binding MoveCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Text}" />
<MenuFlyoutItem Text="Business" Command="{Binding MoveCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Text}" />
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
</HyperlinkButton>
班级:
public class MoveContactBehavior : DependencyObject, IAction
{
public object Execute(object sender, object parameter)
{
var senderElement = sender as FrameworkElement;
FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
flyoutBase.ShowAt(senderElement);
return null;
}
}
视图模型:
public HomeViewModel()
{
MoveCommand = new DelegateCommand(MoveContact);
}
public DelegateCommand MoveCommand
{
get;
private set;
}
private void MoveContact(object e)
{
var targetCategory = e as string;
SelectedCategory.Contacts.Remove(SelectedContact);
switch(targetCategory)
{
case "Family":
{
FamilyCategory.Contacts.Add(SelectedContact);
break;
}
case "Friends":
{
FriendsCategory.Contacts.Add(SelectedContact);
break;
}
case "Business":
{
BusinessCategory.Contacts.Add(SelectedContact);
break;
}
default:
{
throw new NotImplementedException();
}
}
}
委托命令:
public class DelegateCommand : ICommand
{
Func<object, bool> canExecute;
Action<object> executeAction;
public DelegateCommand(Action<object> executeAction)
: this(executeAction, null)
{
}
public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute)
{
if (executeAction == null)
{
throw new ArgumentNullException("executeAction");
}
this.executeAction = executeAction;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
bool result = true;
Func<object, bool> canExecuteHandler = this.canExecute;
if (canExecuteHandler != null)
{
result = canExecuteHandler(parameter);
}
return result;
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
EventHandler handler = this.CanExecuteChanged;
if (handler != null)
{
handler(this, new EventArgs());
}
}
public void Execute(object parameter)
{
this.executeAction(parameter);
}
}