WPF DataGrid水平单元格选择

时间:2014-09-08 12:12:07

标签: c# wpf datagrid

我必须实现一个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中它不起作用:(

1 个答案:

答案 0 :(得分:1)

尝试将此事件处理程序添加到代码隐藏中的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;
    }
}