当绑定属性更改时,ListView 分组不会更新

2024-04-09

我正在使用依赖项属性 GroupDescription 根据列表视图项目源的属性对 WPF 列表视图中的项目进行分组。

我的问题是,仅当 GroupDescription 值更改时才会更新分组,而不是在列表视图源中项目的绑定属性更改后分组才会更新。

在下面的示例中,GroupDescription 设置为城市,从而生成“城市:汉堡”的组描述。但是,当更改项目的城市属性时,列表视图中的分组不会更新,这意味着“城市:汉堡”组中将存在一个包含城市“柏林”的项目。

仅当 GroupDescription 更新后,分组才会更新。我尝试使用 PersonPropertyChanged 方法找到解决方法,该方法将 GroupDescription 更改为 PersonId 并立即返回 City。然而,这种解决方法会导致列表视图总是跳回顶部,以防滚动位置位于列表视图的中间或末尾。当使用包含数百个属性不断变化的条目的列表视图时,这真的很烦人。

有没有办法可以在项目属性更改后“更新”分组,而无需列表视图跳回顶部?

预先感谢您的任何帮助! 托马斯

分组列表视图.cs

using System.Windows.Controls;
using System.Windows;
using System.Windows.Data;

namespace WpfApplication
{
    /// <summary>
    /// Enhanced list view based on WPF ListView with dependency properties for GroupDescriptions
    /// </summary>
    public class GroupingListView : ListView
    {
        /// <summary>
        /// Dependency property for group descriptions
        /// </summary>
        public string GroupDescription
        {
            get { return (string)GetValue(GroupDescriptionProperty); }
            set { SetValue(GroupDescriptionProperty, value); }
        }

        /// <summary>
        /// Using a DependencyProperty as the backing store for GroupDescription.  This enables animation, styling, binding, etc...
        /// </summary>
        public static readonly DependencyProperty GroupDescriptionProperty =
            DependencyProperty.Register("GroupDescription",
                                        typeof(string),
                                        typeof(GroupingListView),
                                        new UIPropertyMetadata(string.Empty, GroupDescriptionChanged));

        private static void GroupDescriptionChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            var control = source as GroupingListView;
            // Stop if source is not of type DetailedListView
            if (control == null) return;

            // Stop if myView is not available, myView can not group, groupdescription missing\
            // or the argument is empty
            var myView = (CollectionView)CollectionViewSource.GetDefaultView(control.ItemsSource);
            if (myView == null || !myView.CanGroup || (string) args.NewValue == string.Empty ||
                myView.GroupDescriptions == null)
            {
                return;
            }
            myView.GroupDescriptions.Clear();
            // If a group description already
            if(myView.GroupDescriptions.Count > 0)
            {
                var prop = myView.GroupDescriptions[0] as PropertyGroupDescription;
                if(prop != null)
                {
                    if(!prop.PropertyName.Equals((string)args.NewValue))
                    {
                        myView.GroupDescriptions.Clear();
                    }
                }
            }

            // Stop if at this point a group description still exists. This means the newValue is
            // equal to the old value and nothing needs to be changed
            if (myView.GroupDescriptions.Count != 0) return;

            // If this code is reached newValue is different than the current groupDescription value
            // therefore the newValue has to be added as PropertyGroupDescription
            var groupDescription = new PropertyGroupDescription((string)args.NewValue);
            // Clear and add the description only if it's not already existing
            myView.GroupDescriptions.Add(groupDescription);
        }
    }
}

主窗口.xaml

<Window x:Class="WpfApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication="clr-namespace:WpfApplication"
        Title="MainWindow" Height="300" Width="300">
    <StackPanel>
        <Button Content="Change" Click="btnChangeCity" Height="22"/><Button Content="Change back" Click="btnChangeCityBack" Height="22"/>
        <WpfApplication:GroupingListView ItemsSource="{Binding Persons}" Height="200"
                                         GroupDescription="{Binding GroupDescription}" x:Name="GroupingListView">
            <ListView.GroupStyle>
                <GroupStyle>
                    <GroupStyle.HeaderTemplate>
                        <DataTemplate>
                            <Grid HorizontalAlignment="Stretch">
                                <Border HorizontalAlignment="Stretch" BorderBrush="Transparent" BorderThickness="1" CornerRadius="3">
                                    <Border HorizontalAlignment="Stretch" BorderBrush="LightGray" BorderThickness="0,0,0,1" CornerRadius="0">
                                        <StackPanel Orientation="Horizontal">
                                            <TextBlock Foreground="LightGray" Text="{Binding GroupDescription, ElementName=GroupingListView}"/>
                                            <TextBlock Foreground="LightGray" Text=" : "/>
                                            <TextBlock Foreground="LightGray" Text="{Binding Name}"  HorizontalAlignment="Stretch"/>
                                        </StackPanel>
                                    </Border>
                                </Border>
                            </Grid>
                        </DataTemplate>
                    </GroupStyle.HeaderTemplate>
                </GroupStyle>
            </ListView.GroupStyle>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="PersonId" Width="100">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock TextTrimming="CharacterEllipsis" Text="{Binding PersonId, Mode=Default}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="City" Width="100">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock TextTrimming="CharacterEllipsis" Text="{Binding City, Mode=Default}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </WpfApplication:GroupingListView>
    </StackPanel>
</Window>

MainWindow.xaml.cs

using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;

namespace WpfApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : INotifyPropertyChanged
    {
        public class Person : INotifyPropertyChanged
        {


            public Person(string personId, string city)
            {
                PersonId = personId;
                City = city;
            }

            private string _personId;
            private string _city;

            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string name)
            {
                PropertyChangedEventHandler pc = PropertyChanged;
                if (pc != null)
                    pc(this, new PropertyChangedEventArgs(name));
            }

            public string PersonId
            {
                get { return _personId; }
                set { _personId = value; OnPropertyChanged("PersonId"); }
            }

            public string City
            {
                get { return _city; }
                set { _city = value; OnPropertyChanged("City"); }
            }


        }

        public ObservableCollection<Person> Persons { get; set; }

        public string GroupDescription
        {
            get { return _groupDescription; }
            set { _groupDescription = value; OnPropertyChanged("GroupDescription"); }
        }

        private string _groupDescription;

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            GroupDescription = "City";
            Persons = new ObservableCollection<Person>();
            Persons.CollectionChanged += PersonsCollectionChanged;
            Persons.Add(new Person("1", "Hamburg"));
            Persons.Add(new Person("2", "Hamburg"));
            Persons.Add(new Person("3", "Hamburg"));
            Persons.Add(new Person("4", "Hamburg"));
            Persons.Add(new Person("5", "Hamburg"));
            Persons.Add(new Person("6", "Hamburg"));
            Persons.Add(new Person("7", "Hamburg"));
            Persons.Add(new Person("8", "Hamburg"));
            Persons.Add(new Person("9", "Berlin"));
            Persons.Add(new Person("10", "Hamburg"));
            Persons.Add(new Person("11", "Hamburg"));
            Persons.Add(new Person("12", "Munich"));
            Persons.Add(new Person("13", "Munich"));
            OnPropertyChanged("Persons");
        }

        public void PersonsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach(Person item in e.OldItems)
                {
                    //Removed items
                    item.PropertyChanged -= PersonPropertyChanged;
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach(Person item in e.NewItems)
                {
                    //Added items
                    item.PropertyChanged += PersonPropertyChanged;
                }     
            }       
        }   

    public void PersonPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        //GroupDescription = "PersonId";
        //GroupDescription = "City";
    }


        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler pc = PropertyChanged;
            if (pc != null)
                pc(this, new PropertyChangedEventArgs(name));
        }

        private void btnChangeCity(object sender, System.Windows.RoutedEventArgs e)
        {
            Persons[0].City = "Berlin";
        }

        private void btnChangeCityBack(object sender, System.Windows.RoutedEventArgs e)
        {
            Persons[0].City = "Hamburg";
        }

    }
}

我意识到这已经很晚了,但如果您使用 .NET4.5 或更高版本,您可以使用实时分组功能,我认为这将完全满足您的要求。

例如,而不是绑定ListView ItemsSource直接到Persons,你可以绑定到CollectionViewSource它本身绑定到Persons:

<Window.Resources>
    <CollectionViewSource x:Key="PersonsViewSource" Source="{Binding Persons}" IsLiveGroupingRequested="True"> 
         <CollectionViewSource.GroupDescriptions>
              <PropertyGroupDescription PropertyName="GroupName" />
         </CollectionViewSource.GroupDescriptions>            
    </CollectionViewSource>
</Window.Resources>

如上所示,您只需添加属性IsLiveGroupingRequested="True",然后添加要重新分组的属性名称。

当。。。的时候GroupName属性更改(通过您使用INotifyPropertyChanged),相关项目将自行移动到正确的组中ListView,不改变任何其他东西。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当绑定属性更改时,ListView 分组不会更新 的相关文章

  • C# 和 Javascript SHA256 哈希的代码示例

    我有一个在服务器端运行的 C 算法 它对 Base64 编码的字符串进行哈希处理 byte salt Convert FromBase64String serverSalt Step 1 SHA256Managed sha256 new S
  • 将数组向左或向右旋转一定数量的位置,复杂度为 o(n)

    我想编写一个程序 根据用户的输入 正 gt 负 include
  • pthread_cond_timedwait() 和 pthread_cond_broadcast() 解释

    因此 我在堆栈溢出和其他资源上进行了大量搜索 但我无法理解有关上述函数的一些内容 具体来说 1 当pthread cond timedwait 因为定时器值用完而返回时 它如何自动重新获取互斥锁 互斥锁可能被锁定在其他地方 例如 在生产者
  • 将布尔参数传递给 SQL Server 存储过程

    我早些时候问过这个问题 我以为我找到了问题所在 但我没有 我在将布尔参数传递给存储过程时遇到问题 这是我的 C 代码 public bool upload false protected void showDate object sende
  • 指针问题(仅在发布版本中)

    不确定如何描述这一点 但我在这里 由于某种原因 当尝试创建我的游戏的发布版本进行测试时 它的敌人创建方面不起作用 Enemies e level1 3 e level1 0 Enemies sdlLib 500 2 3 128 250 32
  • Json.NET - 反序列化接口属性引发错误“类型是接口或抽象类,无法实例化”

    我有一个类 其属性是接口 public class Foo public int Number get set public ISomething Thing get set 尝试反序列化Foo使用 Json NET 的类给我一条错误消息
  • Cython 和类的构造函数

    我对 Cython 使用默认构造函数有疑问 我的 C 类 Node 如下 Node h class Node public Node std cerr lt lt calling no arg constructor lt lt std e
  • WPF TabControl,用C#代码更改TabItem的背景颜色

    嗨 我认为这是一个初学者的问题 我搜索了所有相关问题 但所有这些都由 xaml 回答 但是 我需要的是后台代码 我有一个 TabControl 我需要设置其项目的背景颜色 我需要在选择 取消选择和悬停时为项目设置不同的颜色 非常感谢你的帮助
  • Qt moc 在头文件中实现?

    是否可以告诉 Qt MOC 我想声明该类并在单个文件中实现它 而不是将它们拆分为 h 和 cpp 文件 如果要在 cpp 文件中声明并实现 QObject 子类 则必须手动包含 moc 文件 例如 文件main cpp struct Sub
  • 指针减法混乱

    当我们从另一个指针中减去一个指针时 差值不等于它们相距多少字节 而是等于它们相距多少个整数 如果指向整数 为什么这样 这个想法是你指向内存块 06 07 08 09 10 11 mem 18 24 17 53 7 14 data 如果你有i
  • 如何将单个 char 转换为 int [重复]

    这个问题在这里已经有答案了 我有一串数字 例如 123456789 我需要提取它们中的每一个以在计算中使用它们 我当然可以通过索引访问每个字符 但是如何将其转换为 int 我研究过 atoi 但它需要一个字符串作为参数 因此 我必须将每个字
  • 使用 DataBindingComponent 的 Inflate 方法

    当 Glide 成功渲染图像后 我在更新文本视图时看到此错误 致命异常 java lang IllegalStateException 必需 CustomBinding 类中的 DataBindingComponent 为 null 绑定适
  • 将 xml 反序列化为类,list<> 出现问题

    我有以下 XML
  • 插入记录后如何从SQL Server获取Identity值

    我在数据库中添加一条记录identity价值 我想在插入后获取身份值 我不想通过存储过程来做到这一点 这是我的代码 SQLString INSERT INTO myTable SQLString Cal1 Cal2 Cal3 Cal4 SQ
  • 控制到达非 void 函数末尾 -wreturn-type

    这是查找四个数字中的最大值的代码 include
  • 32 位到 64 位内联汇编移植

    我有一段 C 代码 在 GNU Linux 环境下用 g 编译 它加载一个函数指针 它如何执行并不重要 使用一些内联汇编将一些参数推送到堆栈上 然后调用该函数 代码如下 unsigned long stack 1 23 33 43 save
  • x86 上未对齐的指针

    有人可以提供一个示例 将指针从一种类型转换为另一种类型由于未对齐而失败吗 在评论中这个答案 https stackoverflow com questions 544928 reading integer size bytes from a
  • ASP.NET MVC 6 (ASP.NET 5) 中的 Application_PreSendRequestHeaders 和 Application_BeginRequest

    如何在 ASP NET 5 MVC6 中使用这些方法 在 MVC5 中 我在 Global asax 中使用了它 现在呢 也许是入门班 protected void Application PreSendRequestHeaders obj
  • C 中的异或运算符

    在进行按位操作时 我在确定何时使用 XOR 运算符时遇到一些困难 按位与和或非常简单 当您想要屏蔽位时 请使用按位 AND 常见用例是 IP 寻址和子网掩码 当您想要打开位时 请使用包含或 然而 XOR 总是让我明白 我觉得如果在面试中被问
  • 如何在 C++ BOOST 中像图形一样加载 TIFF 图像

    我想要加载一个 tiff 图像 带有带有浮点值的像素的 GEOTIFF 例如 boost C 中的图形 我是 C 的新手 我的目标是使用从源 A 到目标 B 的双向 Dijkstra 来获得更高的性能 Boost GIL load tiif

随机推荐