我的收藏看起來很好,因爲我能夠使用ListView,並且它正確響應添加,但是當我將一個listview嵌套到UserControl時,它不會。我提供了相關的代碼。如何獲取綁定到ObservableCollection的UserControl派生類來響應添加?
我創建這個時尚用戶控件派生類:
public partial class MyCtrl: UserControl
{
#region Static Properties
public static readonly DependencyProperty ItemsSourceProperty =
ItemsControl.ItemsSourceProperty.AddOwner(
typeof(MyCtrl),
new PropertyMetadata(MyCtrl.ItemsSourcePropertyChangedCallback));
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static void ItemsSourcePropertyChangedCallback(
DependencyObject controlInstance,
DependencyPropertyChangedEventArgs e)
{
MyCtrl myInstance=(MyCtrl)controlInstance;
myInstance.nestedList.ItemsSource=e.NewValue as IEnumerable;
}
}
有了XAML這樣的:
<UserControl x:Class="MyCtrl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<ListView Name="nestedList" />
</Grid>
</UserControl>
我的消費XAML看起來像這樣:
<MyCtrl x:Name="myInstance" ItemsSource="{Binding Path=MyCollection}" />
如果收集的定義如下:
public static readonly DependencyProperty MyCollectionProperty =
DependencyProperty.Register("MyCollection",
typeof(ObservableCollection<MyObject>),
typeof(ConsumingObject),
new PropertyMetadata(new ObservableCollection<MyObject>());
public ObservableCollection<MyObject> MyCollection
{
get { return (ObservableCollection<MyObject>)this.GetValue(MyCollectionProperty); }
set { this.SetValue(MyCollectionProperty, value); }
}
我更喜歡使用AutoMagic。該集合報告添加,因爲當我使用ListView而不是自定義UserControl它的作品。所以不知何故,我不會將更改傳播給嵌套的ListView。 – tillerstarr 2011-04-15 15:45:34
據我所知,列表框控件檢查該數據源是否實現INotifyPropertyChanged並處理PropertyChanged – DarkSquirrel42 2011-04-15 15:50:18