正确的方法是如何将双击事件附加到ListView中的项目,以便在双击列表视图中的项目时,在视图模型中触发相应的事件并具有对单击的项目的引用?
如何以纯净的MVVM方式完成,即在View中没有后台代码?
请注意,在IT技术中,代码后台并不是什么坏事。不幸的是,WPF社区中有很多人对此存在误解。
MVVM模式并不是为了消除代码后台,而是为了将视图部分(外观、动画等)与逻辑部分(工作流程)分开。此外,您可以对逻辑部分进行单元测试。
我知道很多场景下需要编写代码后台,因为数据绑定并不是万能的解决方案。在您的情况下,我会在代码后台文件中处理DoubleClick事件,并将其委托给ViewModel。
这里可以找到使用代码后台但仍符合MVVM分离的示例应用程序:
Win应用程序框架(WAF) - https://github.com/jbe2277/waf
我能够在 .NET 4.5 中让这个工作起来。看起来很简单,不需要第三方库或者代码后台。
<ListView ItemsSource="{Binding Data}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="2">
<Grid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding ShowDetailCommand}"/>
</Grid.InputBindings>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Image Source="..\images\48.png" Width="48" Height="48"/>
<TextBlock Grid.Row="1" Text="{Binding Name}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
InputBindings
从 .NET 3.0 开始提供,在 Silverlight 中 _不可用_。 - Martin我喜欢使用 附加命令行为 和命令。 Marlon Grech 拥有非常好的实现 Attached Command Behaviors 的方式。使用它们,我们可以分配一个样式到 ListView 的 ItemContainerStyle 属性上,这将为每个 ListViewItem 设置命令。
在这里,我们将命令设置为在 MouseDoubleClick 事件上触发,并且 CommandParameter 将是我们所点击的数据对象。在这里,我沿着可视化树向上寻找我正在使用的命令,但您也可以轻松地创建全局应用程序命令。
<Style x:Key="Local_OpenEntityStyle"
TargetType="{x:Type ListViewItem}">
<Setter Property="acb:CommandBehavior.Event"
Value="MouseDoubleClick" />
<Setter Property="acb:CommandBehavior.Command"
Value="{Binding ElementName=uiEntityListDisplay, Path=DataContext.OpenEntityCommand}" />
<Setter Property="acb:CommandBehavior.CommandParameter"
Value="{Binding}" />
</Style>
对于命令,您可以直接实现ICommand,或者使用一些辅助工具,例如来自MVVM Toolkit的工具。
acb:
= AttachedCommandBehavior。代码可以在答案的第一个链接中找到。 - Rachel我发现使用Blend SDK事件触发器可以非常简单和清晰地完成这个操作。干净的MVVM,可重用且没有代码后台。
你可能已经有了类似于这样的东西:
<Style x:Key="MyListStyle" TargetType="{x:Type ListViewItem}">
如果您还没有使用ControlTemplate,现在可以为ListViewItem添加一个像这样的ControlTemplate:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<GridViewRowPresenter Content="{TemplateBinding Content}"
Columns="{TemplateBinding GridView.ColumnCollection}" />
</ControlTemplate>
</Setter.Value>
</Setter>
< p >GridViewRowPresenter将是所有元素“内部”的视觉根,构成列表行元素。现在我们可以在那里插入一个触发器来寻找MouseDoubleClick路由事件,并通过InvokeCommandAction调用命令,就像这样:< /p ><Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<GridViewRowPresenter Content="{TemplateBinding Content}"
Columns="{TemplateBinding GridView.ColumnCollection}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding DoubleClickCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</GridViewRowPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
如果您有位于GridRowPresenter之上的可视元素(可能是网格),您也可以在那里放置触发器。
遗憾的是,双击鼠标事件并不会从每个可视元素生成(例如,它们来自控件,但不来自FrameworkElements)。一种解决方法是从EventTrigger派生一个类,并查找ClickCount为2的MouseButtonEventArgs。这有效地过滤了所有非MouseButtonEvents和所有ClickCount != 2的MoseButtonEvents。
class DoubleClickEventTrigger : EventTrigger
{
protected override void OnEvent(EventArgs eventArgs)
{
var e = eventArgs as MouseButtonEventArgs;
if (e == null)
{
return;
}
if (e.ClickCount == 2)
{
base.OnEvent(eventArgs);
}
}
}
现在我们可以这样编写代码('h'是上面助手类的名称空间):
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<GridViewRowPresenter Content="{TemplateBinding Content}"
Columns="{TemplateBinding GridView.ColumnCollection}">
<i:Interaction.Triggers>
<h:DoubleClickEventTrigger EventName="MouseDown">
<i:InvokeCommandAction Command="{Binding DoubleClickCommand}" />
</h:DoubleClickEventTrigger>
</i:Interaction.Triggers>
</GridViewRowPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
我知道这个讨论已经有一年了,但是在.NET 4中,对于这个解决方案有什么想法吗?我完全同意MVVM的重点不是为了消除代码后台文件。我也非常强烈地认为,仅仅因为某些东西很复杂,并不意味着它更好。以下是我放在代码后台中的内容:
private void ButtonClick(object sender, RoutedEventArgs e)
{
dynamic viewModel = DataContext;
viewModel.ButtonClick(sender, e);
}
当视图创建时,我发现将命令链接起来更加简单:
var r = new MyView();
r.MouseDoubleClick += (s, ev) => ViewModel.MyCommand.Execute(null);
BindAndShow(r, ViewModel);
BindAndShow
看起来是这样的(使用 updatecontrols 和 AvalonDock):private void BindAndShow(DockableContent view, object viewModel)
{
view.DataContext = ForView.Wrap(viewModel);
view.ShowAsDocument(dockManager);
view.Focus();
}
虽然这种方法适用于你打开新视图的任何方法。
<ListView x:Name="list"
Message.Attach="[Event MouseDoubleClick] = [Action ItemActivated(list.SelectedItem)]" >
您可以查看Caliburn的文档和示例以获取更多详细信息。
我使用交互库成功地在 .Net 4.7 框架中实现了此功能。首先,请确保在 XAML 文件中声明命名空间。
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
然后在 ListView 中设置带有其相应 InvokeCommandAction 的事件触发器,如下所示。
视图:
<ListView x:Name="lv" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=AppsSource}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction CommandParameter="{Binding ElementName=lv, Path=SelectedItem}"
Command="{Binding OnOpenLinkCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Developed By" DisplayMemberBinding="{Binding DevelopedBy}" />
</GridView>
</ListView.View>
</ListView>
public class ApplicationModel
{
public string Name { get; set; }
public string DevelopedBy { get; set; }
}
视图模型:
public class AppListVM : BaseVM
{
public AppListVM()
{
_onOpenLinkCommand = new DelegateCommand(OnOpenLink);
_appsSource = new ObservableCollection<ApplicationModel>();
_appsSource.Add(new ApplicationModel("TEST", "Luis"));
_appsSource.Add(new ApplicationModel("PROD", "Laurent"));
}
private ObservableCollection<ApplicationModel> _appsSource = null;
public ObservableCollection<ApplicationModel> AppsSource
{
get => _appsSource;
set => SetProperty(ref _appsSource, value, nameof(AppsSource));
}
private readonly DelegateCommand _onOpenLinkCommand = null;
public ICommand OnOpenLinkCommand => _onOpenLinkCommand;
private void OnOpenLink(object commandParameter)
{
ApplicationModel app = commandParameter as ApplicationModel;
if (app != null)
{
//Your code here
}
}
}
如果您需要实现DelegateCommand类,请参考以下内容。
<ControlTemplate x:Key="SelectedActiveTemplate" TargetType="{x:Type ListViewItem}">
<Border Background="LightBlue" HorizontalAlignment="Stretch">
<!-- Bind the double click to a command in the parent view model -->
<Border.InputBindings>
<MouseBinding Gesture="LeftDoubleClick"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.ItemSelectedCommand}"
CommandParameter="{Binding}" />
</Border.InputBindings>
<TextBlock Text="{Binding TextToShow}" />
</Border>
</ControlTemplate>
<ControlTemplate x:Key="SelectedInactiveTemplate" TargetType="{x:Type ListViewItem}">
<Border Background="Lavender" HorizontalAlignment="Stretch">
<TextBlock Text="{Binding TextToShow}" />
</Border>
</ControlTemplate>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border HorizontalAlignment="Stretch">
<TextBlock Text="{Binding TextToShow}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="True" />
<Condition Property="Selector.IsSelectionActive" Value="True" />
</MultiTrigger.Conditions>
<Setter Property="Template" Value="{StaticResource SelectedActiveTemplate}" />
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="True" />
<Condition Property="Selector.IsSelectionActive" Value="False" />
</MultiTrigger.Conditions>
<Setter Property="Template" Value="{StaticResource SelectedInactiveTemplate}" />
</MultiTrigger>
</Style.Triggers>
</Style>
listviewitem
,他们可能并不关心它是否已经被选中。此外,需要注意的是,高亮效果可能还需要进行调整以匹配 listview
样式。点赞。 - David BentleyListBox
和ListView
上实现。public class ItemDoubleClickBehavior : Behavior<ListBox>
{
#region Properties
MouseButtonEventHandler Handler;
#endregion
#region Methods
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PreviewMouseDoubleClick += Handler = (s, e) =>
{
e.Handled = true;
if (!(e.OriginalSource is DependencyObject source)) return;
ListBoxItem sourceItem = source is ListBoxItem ? (ListBoxItem)source :
source.FindParent<ListBoxItem>();
if (sourceItem == null) return;
foreach (var binding in AssociatedObject.InputBindings.OfType<MouseBinding>())
{
if (binding.MouseAction != MouseAction.LeftDoubleClick) continue;
ICommand command = binding.Command;
object parameter = binding.CommandParameter;
if (command.CanExecute(parameter))
command.Execute(parameter);
}
};
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PreviewMouseDoubleClick -= Handler;
}
#endregion
}
public static class UIHelper
{
public static T FindParent<T>(this DependencyObject child, bool debug = false) where T : DependencyObject
{
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
if (parentObject is T parent)
return parent;
else
return FindParent<T>(parentObject);
}
}
使用方法:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:coreBehaviors="{{Your Behavior Namespace}}"
<ListView AllowDrop="True" ItemsSource="{Binding Data}">
<i:Interaction.Behaviors>
<coreBehaviors:ItemDoubleClickBehavior/>
</i:Interaction.Behaviors>
<ListBox.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding YourCommand}"/>
</ListBox.InputBindings>
</ListView>