WPF DataGrid水平单元格选择

本文关键字:选择 单元格 水平 DataGrid WPF | 更新日期: 2023-09-27 18:21:07

我必须实现一个WPF DataGrid,使用它可以只选择一行中的单元格。我怎样才能做到这一点?我知道属性SelectionUnitSelectionMode,但这两个属性的每一个组合都没有成功。

XAML:

<DataGrid AutoGenerateColumns="True" CanUserAddRows="False" 
    ItemsSource="{Binding DPGridCR}" HeadersVisibility="None" SelectionUnit="Cell"
    SelectionMode="Extended" CanUserResizeRows="False" />

此时此刻,我只能在多行中选择多个单元格,或者只选择一个单元格或选择整行。但我想在一行中选择多个单元格。

编辑:

<UserControl x:Class="DesignerPro.Controls.DZLeerformularGrid"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    xmlns:ViewModel="clr-namespace:ViewModel;assembly=ViewModel"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="300"
    x:Name="DZLeerformularGridControl">
    <UserControl.Resources>
        <ViewModel:DZLeerformularGridViewModel x:Key="ViewModel" />
    </UserControl.Resources>
    <DataGrid AutoGenerateColumns="True" CanUserAddRows="False"
        ItemsSource="{Binding DPGridCR}" HeadersVisibility="None" SelectionUnit="Cell"
        SelectionMode="Extended" CanUserResizeRows="False">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectedCellsChanged">
                <ei:CallMethodAction TargetObject="{Binding Mode=OneWay, Source={StaticResource ViewModel}}" MethodName="DataGrid_SelectedCellsChanged" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </DataGrid>
</UserControl>

使用EventTrigger,我尝试将SelectedCellsChanged-事件绑定到我的ViewModel。您的解决方案在代码隐藏中运行良好,但在我的ViewModel中不起作用:(

WPF DataGrid水平单元格选择

尝试将此事件处理程序添加到代码后面的SelectedCellsChanged事件中:

private void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    var grid = sender as DataGrid;
    if (grid == null || !grid.SelectedCells.Any())
        return;
    var row = grid.Items.IndexOf(grid.SelectedCells[0].Item);
    try
    {
        // Disable the event handler to prevent a stack overflow.
        grid.SelectedCellsChanged -= DataGrid_SelectedCellsChanged;
        // If any of the selected cells don't match the row of the first selected cell,
        // undo the selection by removing the added cells and adding the removed cells.
        if (grid.SelectedCells.Any(c => grid.Items.IndexOf(c.Item) != row))
        {
            e.AddedCells.ToList().ForEach(c => grid.SelectedCells.Remove(c));
            e.RemovedCells.ToList().ForEach(c => grid.SelectedCells.Add(c));
        }
    }
    finally
    {
        // Don't forget to re-enable the event handler.
        grid.SelectedCellsChanged += DataGrid_SelectedCellsChanged;
    }
}