【问题标题】:ListBoxItem stealing Mouse clicks from ListBoxListBoxItem 从 ListBox 窃取鼠标点击
【发布时间】:2012-04-13 11:27:30
【问题描述】:

我在 ListBoxItem 的样式中使用 MouseBindings。

<MouseBinding MouseAction="LeftClick" Command="{Binding    
DataContext.ViewWorkingImprovementAssetCommand}" CommandParameter="{Binding}"/>

具体来说,我使用 LeftClick 命令在视图模型中触发命令。问题是该项目没有在 ListBox 中被选中,因为鼠标事件没有到达列表框。那么有没有办法将事件传递给父控件(ListBox)?

如果我在 ListBox 上为 SelectionChanged 使用交互触发器,我可以让这个东西工作,但问题是重新单击已选择的项目不会像名称所暗示的那样触发事件。当我的列表中只有一项存在问题时。

<i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
         <i:InvokeCommandAction Command="{Binding ViewWorkingImprovementAssetCommand}" 
                                CommandParameter="{Binding ElementName=RemovedImprovementAssetsListBox, Path=SelectedItem}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

有什么想法吗?

【问题讨论】:

  • 我认为我们需要查看 Xaml
  • 正确回答自己的问题并接受答案,答案不属于问题。

标签: wpf xaml listbox mouseevent listboxitem


【解决方案1】:

显然 MouseBinding 窃取了事件并且不会通过它。我使用解决方案中已有的 AttachedBehaviors 解决了这个问题。我认为取自http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/

最终代码解决方案

<cmd:CommandBehaviorCollection.Behaviors>
<cmd:BehaviorBinding Event="MouseLeftButtonDown" 
                    Command="{Binding  RelativeSource={RelativeSource FindAncestor,  AncestorType=UserControl, AncestorLevel=1}, Path=DataContext.ViewWorkingImprovementAssetCommand}" 
                    CommandParameter="{Binding}"/>
</cmd:CommandBehaviorCollection.Behaviors>

【讨论】:

    【解决方案2】:

    在 ListBox 上为 PreviewMouseDown 添加一个处理程序。

    private void myListBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        MyObject entry = null;
    
        // did user click on a list entry?
        var pos = e.GetPosition(myListBox);
        var elem = myListBox.InputHitTest(pos);
        if (elem is FrameworkElement && (elem as FrameworkElement).DataContext != null)
        {
            ListBoxItem item = myListBox.ItemContainerGenerator.ContainerFromItem((elem as FrameworkElement).DataContext) as ListBoxItem;
            entry = item.DataContext as MyObject;
        }
    
        // do something with entry
    
        // if you don't want the event to bubble up, then set e.Handled=true
        // But then you will probably want to set  myListBox.SelectedItem = entry
        e.Handled = true;
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-15
      • 2016-12-30
      • 2019-02-09
      • 1970-01-01
      • 2012-04-13
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多