本文介绍了如何在 WPF 中的 StackPanel 的 MouseEnter 上执行命令绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVVM.

I'm using MVVM.

<ItemsControl ItemsSource="{Binding AllIcons}" Tag="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Label HorizontalAlignment="Right">x</Label>
                <Image Source="{Binding Source}" Height="100" Width="100" />
                <Label HorizontalAlignment="Center" Content="{Binding Title}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

看起来不错.如果我使用以下命令在堆栈面板中放置一个按钮:

That looks fine. If I put a button in the stack panel using this command:

<Button Command="{Binding Path=DataContext.InvasionCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}"/>

我能够捕获命令.但是,我想在鼠标进入堆栈面板时执行命令绑定,而不是在单击按钮时执行.

I'm able to capture the command. However, I want to execute the command binding when the mouse enters the stack panel, not when I click a button.

有什么想法吗?

推荐答案

我的错,输入绑定没有解决问题.您可以为此使用附加属性:

My wrong, input bindings does not solve the problem. You may use attached properties for this:

public static class MouseEnterCommandBinding
{
     public static readonly DependencyProperty MouseEnterCommandProperty = DependencyProperty.RegisterAttached(
  "MouseEnterCommand",
  typeof(ICommand),
  typeof(MouseEnterCommandBinding),
  new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)
);

public static void SetMouseEnterCommand(UIElement element, ICommand value)
{ 
   element.SetValue(MouseEnterCommandProperty, value);
   element.MouseEnter += (s,e) => 
   {
      var uiElement = s as UIElement;
      var command = GetMouseEnterCommand(uiElement); 
      if (command != null && command.CanExecute(uiElement.CommandParameter))
          command.Execute(uiElement.CommandParameter);
   }  
}
public static ICommand GetMouseEnterCommand(UIElement element)
{
    return element.GetValue(MouseEnterCommandProperty) as ICommand;
}

}

这篇关于如何在 WPF 中的 StackPanel 的 MouseEnter 上执行命令绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 14:58