我正在尝试使用
编写自定义WPF控件IEnumerable<object> ItemSource
object SelectedItem
string DisplayPath
as depencency properties。
我在使用object
作为集合项类型时遇到问题。它没有设置我的集合参考。
当我将集合类型更改为隐式类型IEnumerable<MyType>
时,它可以正常工作。
这是我现在拥有的一些代码(不完整,只是属性初始化和使用)
public IEnumerable<object> ItemsSource
{
get { return (IEnumerable<object>) GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register(
"ItemsSource",
typeof (IEnumerable<object>),
typeof (AutoCompleteComboBox),
new UIPropertyMetadata(null));
public object SelectedValue
{
get { return (object) GetValue(SelectedValueProperty); }
set { SetValue(SelectedValueProperty, value); }
}
public static readonly DependencyProperty SelectedValueProperty =
DependencyProperty.Register(
"SelectedValue",
typeof (object),
typeof (AutoCompleteComboBox),
new UIPropertyMetadata(null));
public string DisplayPath
{
get { return (string) GetValue(DisplayPathProperty); }
set { SetValue(DisplayPathProperty, value); }
}
public static readonly DependencyProperty DisplayPathProperty =
DependencyProperty.Register(
"DisplayPath",
typeof (string),
typeof (AutoCompleteComboBox),
new PropertyMetadata(default(string)));
我在使用ItemsSource(null引用)时遇到异常:
private void atb_TextChanged(object sender, TextChangedEventArgs e)
{
if (atb.Text.Length > 0)
{
IEnumerable<object> results = ItemsSource.Where(
delegate(object s)
{
var propertyInfo = s.GetType().GetProperty(DisplayPath);
var value = propertyInfo.GetValue(s, null);
var s1 = value as string;
return s1.ToLower().StartsWith(atb.Text.ToLower());
});
if (results.Any())
{
slb.ItemsSource = results;
slb.Visibility = Visibility.Visible;
}
else
{
slb.Visibility = Visibility.Collapsed;
slb.ItemsSource = null;
}
}
else
{
slb.Visibility = Visibility.Collapsed;
slb.ItemsSource = null;
}
}
我将ObservableCollection与此绑定,再一次,当我将所有object
更改为MyCustomItem
答案 0 :(得分:0)
我终于找到了解决方案。
我已将集合类型更改为IEnumerable
(非通用),在使用点我必须调用ItemsSource.OfType<object>()
才能使用Linq。