1

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); }
}
4

2 に答える 2

0

この質問が役立つかもしれません。myInstanceのDataContextとは何ですか?
コードはこの行に移動できましたか?
myInstance.nestedList.ItemsSource = e.NewValue as IEnumerable;
はいの場合、nestedListはnullですか?

于 2011-04-16T09:38:37.953 に答える
0

ObservableCollection< T > のCollectionChanged場合、イベント ハンドラーを登録したいかもしれません。ItemSource

于 2011-04-15T15:39:35.057 に答える