【发布时间】:2017-11-22 15:15:48
【问题描述】:
我已经构建了一个自定义用户控件,它有一个 IEnumerable 作为输入,它还应该返回一个 IEnumerable。这是为了有一个灵活的控件,可以接收任何对象的集合。这里有一些代码 sn-ps 可以帮助你理解我的问题:
-
物品来源
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(MultiSelectionComboBox), new PropertyMetadata( new PropertyChangedCallback(OnItemsSourcePropertyChanged))); public IEnumerable ItemsSource { get { return (IEnumerable)GetValue(ItemsSourceProperty); } set { SetValue(ItemsSourceProperty, value); } } -
所选项目
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems", typeof(IEnumerable), typeof(MultiSelectionComboBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(MultiSelectionComboBox.OnSelectedItemsChanged))); public IEnumerable SelectedItems { get { return (IEnumerable)GetValue(SelectedItemsProperty); } set { SetValue(SelectedItemsProperty, value); } }
除了构建 SelectedItems 属性的部分之外,我能够让我的控制工作
foreach(string s in appo)
{
IEnumerator en = ItemsSource.GetEnumerator();
while (en.MoveNext())
{
var val = en.Current;
Type type = val.GetType();
PropertyInfo property = type.GetProperty(DisplayMemberPath);
if (property != null)
{
string name = (string)property.GetValue(val, null);
if(name == s)
{
// need something here
}
}
}
}
基本上在if 中,我检查了IEnumeratoren 的当前元素必须包含在SelectedItem 中。问题是我不知道如何在输出中包含这个元素(即 SelectedItems)。
如果您有更好的想法,我也愿意接受不同的方法
【问题讨论】:
-
如果您希望能够将元素添加到现有的 SelectedItems 集合(而不是创建新集合),请将其类型更改为 ICollection,它具有 Add、Remove 和 Clear 方法。
-
不要使用 GetEnumerator 的东西;使用
foreach (var val in ItemsSource) {。 -
它是直接从 IEnumerable 派生的接口,具有添加或删除元素的附加协定。
-
@DanieleSartori 谁提供 SelectedItems 中的集合?如果您创建
IList类型,则强制要求他们必须提供实现IList中所有方法和属性的东西——包括Add()。实际上,您是在坚持他们为您提供某种允许您向其中添加项目的集合类。 -
@DanieleSartori 请改用
IList。
标签: c# wpf ienumerable