wpf - 如何在 WPF 中的 StackPanel 的 MouseEnter 上执行命令绑定(bind)?

标签 wpf vb.net mvvm

我正在使用 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>

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

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

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

有什么想法吗?

最佳答案

我错了,输入绑定(bind)没有解决问题。您可以为此使用附加属性:

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 - 如何在 WPF 中的 StackPanel 的 MouseEnter 上执行命令绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3152389/

相关文章:

c# - 在 MVVM 中处理复制和粘贴(剪贴板)

sql - System.ServiceModel.FaultException SQL错误,是他们结束了吗?

c# - C# ActionCommand :ICommand into VB.net 翻译

html - 如何在 VB.NET xml 字符串文字中嵌入变量 css 样式?

wpf - TextBlock 样式触发器

c# - 带有使用依赖注入(inject)创建的 View 模型的 Prism PopupWindowAction

c# - View 不会随着 viewModel 的变化而更新

wpf - 如何在 XAML 中注入(inject)转换器

wpf - 调整 WPF 列表或网格中的字体大小以正确使用空间

c# - WPF套接字客户端结构