使用MVVM从WPF ListView项目中触发双击事件

时间:2009-06-23 20:35:04

标签: wpf mvvm

在使用MVVM的WPF应用程序中,我有一个带有listview项的usercontrol。在运行时,它将使用数据绑定来为列表视图填充一组对象。

将双击事件附加到列表视图中的项目的正确方法是什么,以便在列表视图中的项目被双击时,视图模型中的相应事件会被触发并且引用该项目被单击?

如何以干净的MVVM方式完成,即View中没有代码?

10 个答案:

答案 0 :(得分:75)

请注意,背后的代码根本不是一件坏事。不幸的是,WPF社区中的很多人都错了。

MVVM不是消除背后代码的模式。它是将视图部分(外观,动画等)与逻辑部分(工作流)分开。此外,您还可以对逻辑部件进行单元测试。

我知道你必须编写代码的足够场景,因为数据绑定不是解决所有问题的方法。在您的方案中,我将在代码隐藏文件中处理DoubleClick事件,并将此调用委托给ViewModel。

使用代码隐藏并仍然实现MVVM分离的示例应用程序可以在这里找到:

WPF应用框架(WAF) - http://waf.codeplex.com

答案 1 :(得分:68)

我能够使用.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>

答案 2 :(得分:44)

我喜欢使用Attached Command Behaviors和命令。 Marlon Grech非常好地实现了附加命令行为。使用这些,我们可以为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中的某些帮助程序。

答案 3 :(得分:13)

我发现使用Blend SDK事件触发器执行此操作非常简单明了。清理MVVM,可重用,无代码隐藏。

你可能已经有类似的东西:

<Style x:Key="MyListStyle" TargetType="{x:Type ListViewItem}">

现在为ListViewItem包含一个ControlTemplate,如果你还没有使用它:

<Setter Property="Template">
  <Setter.Value>
    <ControlTemplate TargetType="{x:Type ListViewItem}">
      <GridViewRowPresenter Content="{TemplateBinding Content}"
                            Columns="{TemplateBinding GridView.ColumnCollection}" />
    </ControlTemplate>
  </Setter.Value>
 </Setter>

GridViewRowPresenter将是组成列表行元素的“内部”的所有元素的可视根。现在我们可以在那里插入一个触发器来查找MouseDoubleClick路由事件,并通过InvokeCommandAction调用命令,如下所示:

<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“以上”的视觉元素(probalby从网格开始),你也可以把Trigger放在那里。

不幸的是,MouseDoubleClick事件不是从每个可视元素生成的(它们来自Controls,但不是来自FrameworkElements)。解决方法是从EventTrigger派生一个类,并查找ClickCount为2的MouseButtonEventArgs。这有效地过滤掉了所有非MouseButtonEvents和所有带有ClickCount!= 2的MoseButtonEvent。

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>

答案 4 :(得分:6)

我意识到这个讨论已经有一年了,但是对于.NET 4,对这个解决方案有什么想法吗?我绝对同意MVVM的观点并不是要消除文件背后的代码。我也非常强烈地感到,因为某些事情很复杂,并不意味着它会更好。以下是我在后面的代码中添加的内容:

    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        dynamic viewModel = DataContext;
        viewModel.ButtonClick(sender, e);
    }

答案 5 :(得分:4)

您可以使用Caliburn的操作功能将事件映射到ViewModel上的方法。假设您的ItemActivated上有ViewModel方法,那么相应的XAML将如下所示:

<ListView x:Name="list" 
   Message.Attach="[Event MouseDoubleClick] = [Action ItemActivated(list.SelectedItem)]" >

有关详细信息,您可以查看Caliburn的文档和样本。

答案 6 :(得分:4)

我发现在创建视图时链接命令更简单:

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();
}

虽然这种方法应该适用于打开新视图的任何方法。

答案 7 :(得分:1)

我在 rushui 中看到了InuptBindings的解决方案,但我仍然无法触及没有文本的ListViewItem区域 - 即使将背景设置为透明,所以我通过使用不同的模板。

此模板适用于已选择ListViewItem且处于活动状态的时间:

<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>

此模板适用于已选择ListViewItem且处于非活动状态的时间:

<ControlTemplate x:Key="SelectedInactiveTemplate" TargetType="{x:Type ListViewItem}">
   <Border Background="Lavender" HorizontalAlignment="Stretch">
      <TextBlock Text="{Binding TextToShow}" />
   </Border>
</ControlTemplate>

这是用于ListViewItem的默认样式:

<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>

我不喜欢的是重复TextBlock及其文本绑定,我不知道我可以在一个位置声明这一点。

我希望这有助于某人!

答案 8 :(得分:0)

这是在ListBoxListView上都可以完成的行为。

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>

答案 9 :(得分:0)

我通过使用交互库成功使用.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>

适应上面的代码应该足以使双击事件在您的ViewModel上起作用,但是我在示例中添加了Model和View Model类,以便您有完整的想法。

型号:

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类。