我正在尝试开发自定义用户控件。在我的用户控件中,我使用两个控件一个列表框和一个文本框。文本框用于过滤列表框中的项目。为此,我的过滤方法遇到了问题。在我的过滤器方法中,我需要将对象转换为 ItemSource 类型。但我不明白我该如何投射它。这是我尝试的代码:
public static readonly DependencyProperty ItemSourceProperty = DependencyProperty.Register("ItemSourrce", typeof(IEnumerable), typeof(SSSearchListBox), new PropertyMetadata(new PropertyChangedCallback(OnItemsSourcePropertyChanged)));
private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as SSSearchListBox;
if (control != null)
control.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
}
private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
// Remove handler for oldValue.CollectionChanged
var oldValueINotifyCollectionChanged = newValue 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.
}
public IEnumerable ItemSourrce
{
get { return (IEnumerable)this.GetValue(ItemSourceProperty); }
set { this.SetValue(ItemSourceProperty, value); }
}
public void TextFiltering(ICollectionView filteredview, DevExpress.Xpf.Editors.TextEdit textBox)
{
string filterText = "";
filteredview.Filter = delegate(object obj)
{
if (String.IsNullOrEmpty(filterText))
{
return true;
}
string str = obj as string; // Problem is here.
// I need to cast obj to my ItemSourrce Data Type.
if (String.IsNullOrEmpty(obj.ToString()))
{
return true;
}
int index = str.IndexOf(filterText, 0, StringComparison.InvariantCultureIgnoreCase);
return index > -1;
};
textBox.EditValueChanging += delegate
{
filterText = textBox.Text;
filteredview.Refresh();
};
}
private void textEdit1_GotFocus(object sender, RoutedEventArgs e)
{
ICollectionView view = CollectionViewSource.GetDefaultView(ItemSourrce);
TextFiltering(view, textEdit1);
}
调用此使用控制:
List<testClass> myList = new List<testClass>();
public void testMethod()
{
for (int i = 0; i < 20; i++)
{
myList.Add(new testClass { testData=i.ToString()});
}
myTestControl.ItemSourrce = myList;
}
public class testClass
{
public string testData { get; set; }
}
谢谢