首页 > 解决方案 > 如何通过 IEditableCollectionView 编辑 ListBox 项目

问题描述

我有一个ListBox绑定ItemsSource到 ViewModel 的ObservableCollection. 现在我正在制作一个自定义控件,它应该操纵ListBox物品。例如,向上/向下移动项目。我不能使用ItemsSource,因为我希望这个控件可以使用变体数据类型,而且我不知道Type它会是什么。我所知道的关于ItemsSource类型的一切——它会是IEnumerable。所以我编写了用于IEditableCollectionView交换相邻项目的属性值的代码。如果ItemsSourceObservableCollection某种复杂类型,它可以正常工作 - ObservableCollection<Customers>

private void ItemsSwapComplex(object originalSource, object originalDestination)
{
    IEditableCollectionView items = ListBoxToManage.Items;
    Type type = originalSource.GetType();

    // Create clones of Source and Destination
    // DOES NOT WORK WITH <string>
    dynamic cloneSource = Activator.CreateInstance(type);
    dynamic cloneDestination = Activator.CreateInstance(type);

    // Copy property values from Original to Clone
    PropertiesCopyComlex(originalSource, cloneSource);
    PropertiesCopyComlex(originalDestination, cloneDestination);

    // Copy new property values to the Source item
    items.EditItem(originalSource);
    object editSource = items.CurrentEditItem;
    PropertiesCopyComlex(cloneDestination, editSource);
    items.CommitEdit();

    // Copy new property values to the Destination item
    items.EditItem(originalDestination);
    object editDestination = items.CurrentEditItem;
    PropertiesCopyComlex(cloneSource, editDestination);
    items.CommitEdit();
}

private void PropertiesCopyComlex(object originalSource, object originalDestination)
{
    foreach (var v in originalSource.GetType().GetProperties())
    {
        v.SetValue(originalDestination, v.GetValue(originalSource));
    }
}

但是如果ItemsSource是一个简单类型的集合,比如ObservableCollection<string>- 它会抛出一个异常,它string没有构造函数。而且我不明白如何使用IEditableCollectionView来编辑简单的字符串ListBox项目。此代码根本不影响ItemsSource

IEditableCollectionView items = ListBoxToManage.Items;

items.EditItem(originalSource);
object editSource = items.CurrentEditItem;
editSource = "New string";
items.CommitEdit();

如何使用IEditableCollectionView编辑单个string项目ItemsSource

更新:这篇文章暗示我的任务是不可能的。必须对字符串使用包装器。对于我的特定任务 - 包装器必须实现INotifyPropertyChanged,并且至少有一个无参数的构造函数

标签: c#wpf

解决方案


如何使用IEditableCollectionView编辑单个字符串项ItemsSource

不能编辑 aSystem.String因为它是不可变的,即它在创建后无法修改。

为什么 .NET 字符串是不可变的?

如果您使用带有string属性的可变包装器,您确实可以修改包装器,但您不能假设T枚举器返回的每种类型都是可变的。


推荐阅读