我正在构建一个WPF UserControl
。为此,我实现了一个ItemSource DependecyProperty
,如下所示:
private IEnumerable MisItems;
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(TextBoxAutoComplete), new PropertyMetadata(new PropertyChangedCallback(OnItemsSourcePropertyChanged)));
private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as TextBoxAutoComplete;
if (control != null)
control.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
}
private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
MisItems = newValue;
// Remove handler for oldValue.CollectionChanged
var oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;
if (null != oldValueINotifyCollectionChanged)
{
oldValueINotifyCollectionChanged.CollectionChanged -= new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
}
// Add handler for newValue.CollectionChanged (if possible)
var newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;
if (null != newValueINotifyCollectionChanged)
{
newValueINotifyCollectionChanged.CollectionChanged += new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
}
}
void newValueINotifyCollectionChanged_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Do your stuff here.
}
ItemsSource
属性由一个IEnumerable
对象表示。现在我需要在这个函数中将其转换为一个Dictionary<object,string>
:
protected SearchResult DoSearch(string searchTerm)
{
if (!string.IsNullOrEmpty(searchTerm))
{
SearchResult sr = new SearchResult();
//var ItemsText = MisItems.GetType();
var p = (List<string>)MisItems;
/*sr.Results = ItemsText.Select((x, i) => new { x, i }).Where(x=>x.ToString().ToUpper().Contains(searchTerm.ToUpper()))
.ToDictionary(a => (object)a.i, a => a.x);*/
return sr;
}
else return new SearchResult();
}
我该如何进行转换?
编辑 更多信息: 我的视图模型具有以下属性:
public List<EnumeradorWCFModel> Clientes { get; set; }
这个属性的数据是由一个 WCF 服务返回的:
Clientes = _svc.Clientes_Enum(sTicket, "");
然后我希望我的UserControl
可以绑定到这个属性。我像这样创建了我的控件:
<autocomplete:TextBoxAutoComplete x:Name="Clientes" ItemsSource = "{Binding Path=Clientes}" DisplayMemberPath="Descripcion" Height="25"/>
Where(x=>x.x.ToString()...
?目前你正调用匿名类的ToString
方法。 - juharrobject
作为字典的键吗? - Dan Field