【问题标题】:How can I get an event or command to fire when the user clicks on a ListViewItem?当用户单击 ListViewItem 时,如何获取要触发的事件或命令?
【发布时间】:2012-06-30 02:53:47
【问题描述】:

我的应用程序 UI 中有一个列表,我想在用户单击列表中的项目时打开一个弹出框。据我所知,ListViewItem 上没有 Click 事件可以帮助我解决这个问题。 SelectionChanged 事件也不起作用,因为用户可以关闭弹出框,我希望能够再次打开它,而无需他们先在列表中选择不同的项目。

这就是我的 ListView 创建代码的样子,值得:

<ListView x:Name="_resultsListView"
          ItemsSource="{Binding AvailableResults}"
          SelectedItem="{Binding SelectedResult}"
          ItemContainerStyle="{StaticResource LoadResultItemStyle}"
          VirtualizingStackPanel.IsVirtualizing="True"
          Style="{DynamicResource DefaultListViewStyle}" BorderThickness="0"/>

谢谢!任何建议将不胜感激。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    HB suggested 的作用是什么,尽管我发现将Events 绑定到Commands 的更持久的解决方案是使用AttachedCommandBehavior,它可以让您将命令附加到几乎任何事件

    <Style TargetType="{x:Type ListViewItem}">
        <Setter Property="local:CommandBehavior.Event" Value="Click" />
        <Setter Property="local:CommandBehavior.Command" Value="{Binding DataContext.MyCommand, ElementName=MyListView}" />
        <Setter Property="local:CommandBehavior.CommandParameter" Value="{Binding }" />
    </Style>
    

    【讨论】:

      【解决方案2】:

      Button 放入ItemTemplate(或ListViewItem.Template 通过ItemContainerStyle 设置)并将其绑定到命令,如果需要,您可以将其设置为不可见。

      【讨论】:

      • 其中一个问题是,当我单击按钮时,该项目没有被选中。有没有办法让 Button 触发它的 Command 并让 ListViewItem 被选中?
      • @Greg 您可以使用触发器根据IsKeyboardFocusWithin 设置IsSelected。更多详情请见my answer here
      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 2015-06-14
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      相关资源
      最近更新 更多