【问题标题】:In WPF, How to change ListBox and ListView selection rule as same way as WinForms?在 WPF 中,如何像 WinForms 一样更改 ListBox 和 ListView 选择规则?
【发布时间】:2011-03-31 02:57:24
【问题描述】:

如何像WinForms一样改变ListBox和ListView的选择规则?

在 WPF 中,如果 ListBox/ListView 中已经选择了一个项目,即使单击 List 的空白区域,选择仍然保留。 在 WinForm/MFC 中,单击空白区域时取消选择。

这非常有用,尤其是在实现方面。

例如,当用户双击 ListBox 中的某个项目时,优选的行为之一如下: -如果用户双击一个项目,它是修改项目的快捷方式,因此将打开配置对话框。 -如果用户双击一个空的区域,它是添加一个新项目的快捷方式,因此将打开文件选择对话框。

要实现这种行为,最好使用 hit-test 来查找点击的项目。 但是,由于 WPF 中的 hit-test 与 WinForm 相比并不那么容易使用, 最简单的方法是在用户双击列表时检查所选项目。

由于列表项选择的行为差异,应用程序是由 WinForm/MFC 制作的,而不是 WPF 制作的。

有没有办法将列表项选择更改为与 WinForm/MFC 相同的方式? 或者,我应该选择不同的方式来实现上述行为吗?

【问题讨论】:

    标签: wpf listview listbox selection


    【解决方案1】:

    以下列表框示例区分双击项目和列表框。

    XAML:

    <Window x:Class="ListBoxTest.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    
        <ListBox 
            ItemsSource="{Binding Path=Data}" 
            MouseDoubleClick="OnListBoxMouseDoubleClick">
            <ListBox.Resources>
                <Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
                    <EventSetter Event="PreviewMouseDoubleClick" Handler="OnItemPreviewMouseDoubleClick" />
                </Style>
            </ListBox.Resources>
        </ListBox>
    
    </Window>
    

    后面的代码:

    using System;
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    
    namespace ListBoxTest
    {
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
    
                Data = new List<string>() { "AAA", "BBB", "CCC" };
                DataContext = this;
            }
    
            public List<string> Data { get; private set; }
    
            private void OnListBoxMouseDoubleClick(object sender, MouseButtonEventArgs e)
            {
                MessageBox.Show("Add new item");
            }
    
            private void OnItemPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
            {
                string content = (sender as ListBoxItem).Content as string;
                MessageBox.Show("Edit " + content);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多