我使用的是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>
有什么想法吗?
答案 0 :(得分: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>
答案 1 :(得分:0)
在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;
}