WPF ListView - 检测何时单击所选项目 [英] WPF ListView - detect when selected item is clicked

查看:34
本文介绍了WPF ListView - 检测何时单击所选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WPF ListView 控件,该控件显示数据绑定项目的列表.

I'm using a WPF ListView control which displays a list of databound items.

<ListView ItemsSource={Binding MyItems}>
    <ListView.View>
        <GridView>
            <!-- declare a GridViewColumn for each property -->
        </GridView>
    </ListView.View>
</ListView>

我正在尝试获得类似于 ListView.SelectionChanged 事件的行为,只是我还想检测是否单击了当前选定的项目.如果再次单击相同的项目(显然),则 SelectionChanged 事件不会触发.

I'm trying to obtain a behavior similar to the ListView.SelectionChanged event, only I want to also detect if the currently selected item is clicked. The SelectionChanged event does not fire if the same item is clicked again (obviously).

解决此问题的最佳(最干净)方法是什么?

What would be the best (cleanest) way to approach this?

推荐答案

使用 ListView.ItemContainerStyle 属性为您的 ListViewItems 提供一个 EventSetter,它将处理 PreviewMouseLeftButtonDown 事件.然后,在处理程序中,检查是否选择了被点击的项目.

Use the ListView.ItemContainerStyle property to give your ListViewItems an EventSetter that will handle the PreviewMouseLeftButtonDown event. Then, in the handler, check to see if the item that was clicked is selected.

XAML:

<ListView ItemsSource={Binding MyItems}>
    <ListView.View>
        <GridView>
            <!-- declare a GridViewColumn for each property -->
        </GridView>
    </ListView.View>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

代码隐藏:

private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var item = sender as ListViewItem;
    if (item != null && item.IsSelected)
    {
        //Do your stuff
    }
}

这篇关于WPF ListView - 检测何时单击所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆