由于ListBox控件的SelectedItems property
是普通属性而
但我的XAML编译器一直给我错误
无法在'SelectedItemsEx'属性上设置'绑定' 输入'MyListBox'。 '绑定'只能在DependencyProperty上设置 DependencyObject。
为什么我的财产不被识别为依赖财产?感谢任何帮助,谢谢!
XAML:
SelectedItemsEx
ListBox'实施:
<MyListBox ItemsSource="{Binding MyData}" SelectedItemsEx="{Binding SelectedEx}"
SelectionMode="Extended"> ... </MyListBox>
答案 0 :(得分:3)
DependencyProperty
字段必须是静态的:
public static readonly DependencyProperty SelectedItemsExProperty = ...
另请注意,为了使派生的ListBox更具可重用性,您不应该限制SelectedItemsEx
属性的类型。请改用IEnumerable
(或IList
,如SelectedItems
)。此外,无需按属性元数据指定默认值,因为它已null
,default(<any reference type>)
也是null
。
但是,只要SelectedItemsEx
属性发生变化,您就会收到通知。因此,您必须通过属性元数据注册更改回调:
public static readonly DependencyProperty SelectedItemsExProperty =
DependencyProperty.Register(
"SelectedItemsEx", typeof(IEnumerable), typeof(MyListBox),
new PropertyMetadata(SelectedItemsExPropertyChanged));
public IEnumerable SelectedItemsEx
{
get { return (IEnumerable)GetValue(SelectedItemsExProperty); }
set { SetValue(SelectedItemsExProperty, value); }
}
private static void SelectedItemsExPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var listBox = (MyListBox)obj;
var oldColl = e.OldValue as INotifyCollectionChanged;
var newColl = e.NewValue as INotifyCollectionChanged;
if (oldColl != null)
{
oldColl.CollectionChanged -= listBox.SelectedItemsExCollectionChanged;
}
if (newColl != null)
{
newColl.CollectionChanged += listBox.SelectedItemsExCollectionChanged;
}
}
private void SelectedItemsExCollectionChanged(
object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
...
}
}