c# - 如何通过 IEditableCollectionView 编辑 ListBox 项目
问题描述
我有一个ListBox
绑定ItemsSource
到 ViewModel 的ObservableCollection
. 现在我正在制作一个自定义控件,它应该操纵ListBox
物品。例如,向上/向下移动项目。我不能使用ItemsSource
,因为我希望这个控件可以使用变体数据类型,而且我不知道Type
它会是什么。我所知道的关于ItemsSource
类型的一切——它会是IEnumerable
。所以我编写了用于IEditableCollectionView
交换相邻项目的属性值的代码。如果ItemsSource
是ObservableCollection
某种复杂类型,它可以正常工作 - 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
,并且至少有一个无参数的构造函数
解决方案
如何使用
IEditableCollectionView
编辑单个字符串项ItemsSource
?
您不能编辑 aSystem.String
因为它是不可变的,即它在创建后无法修改。
如果您使用带有string
属性的可变包装器,您确实可以修改包装器,但您不能假设T
枚举器返回的每种类型都是可变的。
推荐阅读
- python - 如何提供多个输入并全部取 SS
- python - sklearn 中的 ColumnTransformer 实现没有定义 fit 方法,它只是自动调用 fit_transform?
- flutter - 颤振循环轮播卡
- javascript - 如何在 THREE.js 中优化大型 BufferGeometry 上的变化材料
- php - 访问远程数据库
- android - 如何禁用第三方库的特定 Proguard/R8 规则
- php - 查找两个已知坐标之间的坐标
- python - AttributeError: module 'tensorflow.io' has no attribute 'experimental'
- pandas - 存储从数据框获得的值
- reactjs - 无法从 Three.js 导入后处理