WPF的ListView - 检测被点击所选项目时, [英] WPF ListView - detect when selected item is clicked

查看:804
本文介绍了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>

code-背后:

Code-behind:

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天全站免登陆