简体   繁体   English

WinUI 3 在 ctrl 上突出显示列表视图项 - 单击

[英]WinUI 3 Highlight listview item on ctrl - click

I use a listview in single mode and I would like to change its visual aspect when I control-click on a row to show that this row is selected.我在单一模式下使用列表视图,当我按住 Control 键并单击一行以显示该行已被选中时,我想更改其视觉方面。 I can't use SelectionMode="Multiple" because it doesn't match the expected result (when I normally click on a row, an action is triggered and when I select several rows via ctrl - click, a button appears to perform an action on all selected rows).我不能使用 SelectionMode="Multiple" 因为它与预期结果不匹配(当我通常单击一行时,会触发一个操作,当我 select 通过 ctrl 单击几行时,会出现一个按钮来执行一个操作在所有选定的行上)。

I have set some attributes on my listview like我在我的列表视图上设置了一些属性,比如

IsItemClickEnabled="True" ItemClick="Results_ItemClick"

In Results_ItemClick, I check if the control key is pressed and I would like it to stay highlighted if I move my mouse to another line.在 Results_ItemClick 中,我检查是否按下了控制键,如果我将鼠标移到另一行,我希望它保持突出显示。 I tried with VisualStateManager but I have the impression that moving the mouse cancels the behavior.我尝试使用 VisualStateManager,但我的印象是移动鼠标会取消该行为。

VisualStateManager.GoToState(sender as Control, "Selected", true);

I thought of adding the item to the SelectedItems of the listview but SelectedItems doesn't allow the addition.我想将项目添加到列表视图的 SelectedItems,但 SelectedItems 不允许添加。

Is there a way to do this?有没有办法做到这一点?

Thank you.谢谢。

You can do it this way:你可以这样做:

MainPageViewModel.cs MainPageViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;

namespace ListViewTests;

public class Item
{
    public int Id { get; set; }

    public string Text { get; set; } = string.Empty;
}

public partial class MainPageViewModel : ObservableObject
{
    [ObservableProperty]
    private ObservableCollection<Item> items = new();

    public MainPageViewModel()
    {
        for (int i = 0; i < 10000; i++)
        {
            Items.Add(new Item { Id = Items.Count + 1, Text = $"Item {i + 1}" });
        }
    }
}

MainPage.xaml主页.xaml

<Page
    x:Class="ListViewTests.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:ListViewTests"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    mc:Ignorable="d">

    <Grid RowDefinitions="Auto,*">
        <StackPanel
            Grid.Row="0"
            Orientation="Horizontal">
            <TextBlock Text="Operations" />
            <Button
                x:Name="ProcessSelectedItemsButton"
                Click="ProcessSelectedItemsButton_Click"
                Content="Process selected items"
                Visibility="Collapsed" />
        </StackPanel>
        <ListView
            x:Name="ListViewControl"
            Grid.Row="1"
            IsItemClickEnabled="True"
            ItemsSource="{x:Bind ViewModel.Items, Mode=OneWay}"
            SelectionChanged="ListViewControl_SelectionChanged"
            SelectionMode="Extended">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="local:Item">
                    <Grid ColumnDefinitions="30,*,Auto">
                        <TextBlock
                            Grid.Column="0"
                            Text="{x:Bind Id, Mode=OneWay}" />
                        <TextBlock
                            Grid.Column="1"
                            Text="{x:Bind Text, Mode=OneWay}" />
                        <Button
                            Grid.Column="2"
                            Click="ListItemButton_Click"
                            Content="Ctrl + Click to select multiple items" />
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>

MainPage.xaml.cs MainPage.xaml.cs

using Microsoft.UI.Input;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Data;
using System.Diagnostics;
using System.Linq;
using Windows.System;
using Windows.UI.Core;

namespace ListViewTests;

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    public MainPageViewModel ViewModel { get; } = new();

    public static bool IsControlKeyDown()
    {
        return InputKeyboardSource
            .GetKeyStateForCurrentThread(VirtualKey.Control)
            .HasFlag(CoreVirtualKeyStates.Down);
    }

    private void ProcessSelectedItemsButton_Click(object sender, RoutedEventArgs _)
    {
        foreach (Item item in this.ListViewControl.SelectedItems.OfType<Item>())
        {
            // Do your logic here...
            Debug.WriteLine($"Processed Item Id: {item.Id} Text: {item.Text}.");
        }
    }

    private void ListItemButton_Click(object sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            if (IsControlKeyDown() is false)
            {
                ItemIndexRange allItemsRange = new(
                    firstIndex: 0,
                    length: (uint)this.ListViewControl.Items.Count);
                this.ListViewControl.DeselectRange(allItemsRange);
            }

            int itemIndex = this.ListViewControl.Items.IndexOf(button.DataContext);
            ItemIndexRange selectedItemRange = new(
                firstIndex: itemIndex,
                length: 1);
            this.ListViewControl.SelectRange(selectedItemRange);
        }
    }

    private void ListViewControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        this.ProcessSelectedItemsButton.Visibility = (sender as ListView)?.SelectedItems.Count > 1
            ? Visibility.Visible
            : Visibility.Collapsed;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM