我的集合看起来不错,因为我可以使用 ListView 并且它可以正确响应添加,但是当我将 listview 嵌套到 UserControl 中时它不会。我已经提供了相关的代码。
我以这种方式创建了一个 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); }
}