我有一个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
编辑ItemsSource
的单个string
项目
更新:this post暗示我的任务不可能完成。必须对字符串使用包装。对于我的特定任务,包装器必须实现INotifyPropertyChanged
,并且至少有一个无参数的构造函数
发布于 2019-05-31 17:59:11
如何使用
IEditableCollectionView
编辑ItemsSource
的单个字符串项?
您不能编辑System.String
,因为它是不可变的,即它在创建后不能被修改。
如果使用具有string
属性的可变包装器,则确实可以修改包装器,但不能假定枚举器返回的每个类型T
都是可变的。
https://stackoverflow.com/questions/56386375
复制相似问题