首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何通过IEditableCollectionView编辑ListBox项目

如何通过IEditableCollectionView编辑ListBox项目
EN

Stack Overflow用户
提问于 2019-05-31 06:24:51
回答 1查看 66关注 0票数 0

我有一个ListBox,它的ItemsSource绑定到ViewModel的ObservableCollection。现在,我正在制作一个自定义控件,它应该操作ListBox项。例如,向上/向下移动项目。我不能使用ItemsSource,因为我想让这个控件处理不同的数据类型,而我不知道它会是什么Type。我只知道ItemsSource类型--它将是IEnumerable。因此,我编写了使用IEditableCollectionView来交换相邻项的属性值的代码。如果ItemsSource是某种复杂类型的ObservableCollection - ObservableCollection<Customers>,那么它工作得很好。

代码语言:javascript
复制
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

代码语言:javascript
复制
IEditableCollectionView items = ListBoxToManage.Items;

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

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

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

EN

回答 1

Stack Overflow用户

发布于 2019-05-31 17:59:11

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

您不能编辑System.String,因为它是不可变的,即它在创建后不能被修改。

Why .NET String is immutable?

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56386375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档