2009-07-08 10 views
2

XAMLからDataTemplate参照自体を作成する方法はありますか?この特定のケースでは、同じDataTemplate内に含まれるListBoxからDataTemplateを参照しようとしています。ここで私が望む解決策はありますが、これはうまくいきません。ListBoxのネストされたDataTemplates

<DataTemplate x:Key="nestedItem" DataType="{x:Type local:NestedItem}"> 
    <Expander Header="{Binding Path=Name}"> 
     <ListBox ItemsSource="{Binding Path=Items}" x:Name="itemsList" 
     ItemTemplate="{StaticResource nestedItem}"/> 
    </Expander> 
    </DataTemplate> 

ここに私が現在使っている解決策があります。背後にあるコードで

<DataTemplate x:Key="nestedItem" DataType="{x:Type local:NestedItem}"> 
    <Expander Header="{Binding Path=Name}" Expanded="OnItemExpanded"> 
     <ListBox ItemsSource="{Binding Path=Items}" x:Name="itemsList"/> 
    </Expander> 
    </DataTemplate> 

private void OnItemExpanded(object sender, RoutedEventArgs e) 
    { 
    if (e.OriginalSource != sender) return; 
    var source = (Expander) sender; 
    ListBox listBox = source.FindName("itemsList") as ListBox; 
    NestedItem item = source.DataContext as NestedItem; 
    listBox.ItemsSource = item.Items; 
    listBox.ItemTemplate = (DataTemplate) FindResource("nestedItem"); 
    } 

答えて

3

あなたが望むよう、それが動作する代わりに、StaticResourceのDynamicResourceであることをあなたの内の参照を変更した場合。これは、StaticResourceとDynamicResourceがResourceアイテムを実際に探す方法でthere are some differencesです。あなたには、いくつかのコードを使用して気にしない場合

<DataTemplate x:Key="Local_NestedItem" 
       DataType="{x:Type local:NestedItem}"> 
    <Expander Header="{Binding Path=Name}"> 
     <ListBox ItemsSource="{Binding Path=Items}" 
      x:Name="itemsList" 
      ItemTemplate="{DynamicResource Local_NestedItem}" /> 
    </Expander> 
</DataTemplate> 

はまた、別の良いオプションが使用することですDataTemplateSelector

+0

私はDynamicResourceをテストしていませんでした。私の一部で間違いがありましたが、確かにそれはうまくいきます。私はすでにオブジェクトの型に基づいてテンプレートを変更するコレクション内のいくつかのアイテムのためのDataTemplateSelectorを持っていました(これはジェネリックコレクションです)。ありがとう! –

0

あなたが最初のソリューションのための代わりのDataTemplateのHierarchicalDataTemplateを使用してみましたか? あなたのケースではテストしませんでしたが、ツリービューの場合は通常そのように動作します。

+0

私は、テンプレートがTextBoxを含んでいて、ユーザがTreeViewItemsではなく、ボックス間で順番にタブする必要があったため、タブで問題が発生していました。 TreeViewItemタブイベントを処理するのに時間がかかっていました。 –

+0

私は、そのナビゲーションは確かに迷惑になることがわかります。たぶんそれはいくつかの特殊なtreeview-controlテンプレートで動作しますが、とにかく実用的な解決策があります。 –