c# - 以编程方式取消选择 DataGrid 中的行

标签 c# wpf datagrid selection wpfdatagrid

我正在努力寻找解决方案。

我想做的是仅使 DataGrid 中的某些行可选。 SelectionMode 为 FullRow。一个例子是,如果用户尝试拖动选择几行,而我不想选择其中一行。在这种情况下,我希望仍然选择有效行,但不选择无效行。

有什么想法吗?

最佳答案

This guy wanted to do something alike with a ListBox 。我相信该解决方案也可以适用于 DataGrid。

编辑

public static class DataGridRowEx
{
    public static bool GetCanSelect(DependencyObject obj)
    {
        return (bool)obj.GetValue(CanSelectProperty);
    }
    public static void SetCanSelect(DependencyObject obj, bool value)
    {
        obj.SetValue(CanSelectProperty, value);
    }
    public static readonly DependencyProperty CanSelectProperty =
        DependencyProperty.RegisterAttached("CanSelect", typeof(bool), typeof(DataGridRowEx), new UIPropertyMetadata(true, OnCanSelectChanged));

    private static void OnCanSelectChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        var item = sender as DataGridRow;
        if (item == null)
            return;

        if ((bool)args.NewValue)
        {
            item.Selected -= RowSelected;
        }
        else
        {
            item.Selected += RowSelected;
            item.IsSelected = false;
        }
    }

    private static void RowSelected(object sender, RoutedEventArgs e)
    {
        var item = sender as DataGridRow;
        if (item == null)
            return;

        item.Dispatcher.BeginInvoke((Action)(()=>
        item.IsSelected = false));
    }
}

测试它:

public class ViewModel : INotifyPropertyChanged
{
    #region INotifyPropertyChanged values

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion


    public List<Dummy> Elements { get; set; }

    public ViewModel()
    {
        this.Elements = new List<Dummy>(){
            new Dummy() { CanSelect =true, MyProperty = "Element1"},
            new Dummy() { CanSelect =false, MyProperty = "Element2"},
            new Dummy() { CanSelect =true, MyProperty = "Element3"},
            new Dummy() { CanSelect =false, MyProperty = "Element4"},
            new Dummy() { CanSelect =true, MyProperty = "Element5"},
            new Dummy() { CanSelect =true, MyProperty = "Element6"},
            new Dummy() { CanSelect =true, MyProperty = "Element7"},
            new Dummy() { CanSelect =true, MyProperty = "Element8"},
            new Dummy() { CanSelect =false, MyProperty = "Element9"},
        };
    }
}

public class Dummy
{
    public bool CanSelect { get; set; }

    public string MyProperty { get; set; }

    public override string ToString()
    {
        return this.MyProperty;
    }
}

<Window x:Class="WpfApplication1.MainWindow"
    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:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:WpfApplication1"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="525"
    Height="350"
    mc:Ignorable="d">
<Window.Resources>
    <Style x:Key="DataGridRowStyle" TargetType="{x:Type DataGridRow}">
        <Setter Property="local:DataGridRowEx.CanSelect" Value="{Binding CanSelect}" />
    </Style>
</Window.Resources>
<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>
<Grid x:Name="LayoutRoot">
    <DataGrid ItemsSource="{Binding Elements}"
              RowStyle="{DynamicResource DataGridRowStyle}"
              SelectionUnit="FullRow" />
</Grid>
</Window>

即使按下 Shift 键,它也可以进行多项选择。与 ListBoxItem 解决方案的唯一显着区别是取消选择必须使用 Dispatcher.BeginInvoke 排队,不知道为什么。 此方法的唯一警告是,如果 DataGrid 具有单一选择,则尝试选择不可选择的项目会取消选择当前选定的项目;如果 DataGrid 具有扩展选择,则会取消选择所有项目。

关于c# - 以编程方式取消选择 DataGrid 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13628085/

相关文章:

c# - 如果 MySql C# 中不存在则插入数据

c# - 将 string[] 转换为 ObservableCollection<string>

c# - 如何在 MVVM (.NET MAUI) 中为自定义控件提供命令属性

c# - 触摸屏上的 WPF 模态对话框

UWP 工具包 DataGrid 删除选定边框

c# - 如何替换字符串中找到的列表中的大量字符串值

WPF 主题错误 : Cannot resolve all property references in the property path

c# - 如何避免在 WPF 中递归触发事件?

c# - 忽略数据集中不存在的列(绑定(bind)字段)

WPF - DataGrid 列标题对齐