微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WPF DataGrid C# ObservableCollection.Insert() 中断 IsSelected

如何解决WPF DataGrid C# ObservableCollection.Insert() 中断 IsSelected

我的 DataGrid 中有以下行为:

我有一个 ObservableCollection myGrid。 MyType 包含为 INotifyPropertyChanged 实现的 IsSelected 属性。这很好用,而我只使用 myGrid.Add(newItem);

但是一旦我使用 myGrid.Insert(index,newItem);并且 index 不是最后一个位置,IsSelected 属性不再设置。 因此无法移除这些项目。

我将 IsSelected 用于 removeButton,因此我可以从 myGrid 中删除选定的项目。 我想插入行以按逻辑顺序显示条目。

有没有人看到这个并找到解决方案?我在互联网上找不到答案。 我的解决方法是清除 ObservableCollection 并按正确顺序添加所有项目。

我使用的是 .Net Framework 4.8

编辑:一个小例子,其中只有第一个插入的项目被正确选择。

主窗口的WPF:

<Window x:Class="ObservableGridInserIsSelected.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ObservableGridInserIsSelected"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDeFinitions>
            <RowDeFinition Height="*"/>
            <RowDeFinition Height="Auto"/>
        </Grid.RowDeFinitions>
        <Grid.ColumnDeFinitions>
            <ColumnDeFinition Width="*"/>
            <ColumnDeFinition Width="*"/>
        </Grid.ColumnDeFinitions>
        <DataGrid Grid.Row="0" Grid.ColumnSpan="2" Grid.Column="0" ItemsSource="{Binding MyGrid}"
                  AutoGenerateColumns="False">
                <DataGrid.Resources>
                <Style targettype="DataGridRow">
                    <Setter Property="IsSelected" Value="{Binding IsSelected,Mode=TwoWay}"/>
                    <Setter Property="VerticalAlignment" Value="Center"/>
                    <Setter Property="VerticalContentAlignment" Value="Center"/>
                </Style>
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridTextColumn Header="IndexName" Binding="{Binding Name}"  IsReadOnly="True" Width="*"/>
            </DataGrid.Columns>
        </DataGrid>
        <Button Grid.Row="1" Grid.Column="0" x:Name="InsertAt0" Content="Insert at Index 0"/>
        <Button Grid.Row="1" Grid.Column="1" x:Name="RemoveSelected" Content="Remove Selected"/>
    </Grid>
</Window>

和 MainWindow CS:

using System.Windows;

namespace ObservableGridInserIsSelected
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new Gridviewmodel();
            DataContext = vm;
            InsertAt0.Click += new RoutedEventHandler(vm.AddButton_Click);
            RemoveSelected.Click += new RoutedEventHandler(vm.RemoveButton_Click);
        }
    }
}

现在是“父”视图模型:

using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;

namespace ObservableGridInserIsSelected
{
    class Gridviewmodel
    {
        private int _usedItems = 0;
        ObservableCollection<GridElementviewmodel> _myGrid = new ObservableCollection<GridElementviewmodel>();
        public ObservableCollection<GridElementviewmodel> MyGrid { get => _myGrid; set => _myGrid = value; }

        public Gridviewmodel()
        {

        }


        public void AddButton_Click(object sender,RoutedEventArgs e)
        {
            _myGrid.Insert(0,new GridElementviewmodel("Item" + (_usedItems++)));
        }
        public void RemoveButton_Click(object sender,RoutedEventArgs e)
        {
            var selectedList = _myGrid.Where(x => x.IsSelected).ToList();
            if (selectedList == null ||
                selectedList.Count <= 0)
                return;

            foreach (var delItem in selectedList)
            {
                _myGrid.Remove(delItem);
            }
        }
    }
}

最后是元素视图模型:

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace ObservableGridInserIsSelected
{
    class GridElementviewmodel : INotifyPropertyChanged
    {

        public bool IsSelected { get; set; }
        public string Name { get; set; }

        public GridElementviewmodel(string name)
        {
            Name = name;
            IsSelected = false;
        }

        #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,e);
            }
        }

        protected void SetProperty<T>(ref T storage,T value,[CallerMemberName] string property = null)
        {
            if (Object.Equals(storage,value)) return;
            storage = value;
            if (PropertyChanged != null)
                PropertyChanged(this,new PropertyChangedEventArgs(property));
        }

        protected void SetProperty(string property = null)
        {

            if (PropertyChanged != null)
                PropertyChanged(this,new PropertyChangedEventArgs(property));
        }
        #endregion
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。