1

WPFでコンテンツを動的に生成しようとしたり、データをバインドした後、問題が発生します。

次のシナリオがあります。TabControl-DataTemplateを介して動的に生成されたTabItems-TabItems内に、バインドしたいDataTemplateによって生成された動的コンテンツ(ListBox)があります。

コードは次のとおりです。

:: TabControl

<TabControl Height="252" HorizontalAlignment="Left" Name="tabControl1" VerticalAlignment="Top" Width="458" Margin="12,12,12,12" ContentTemplate="{StaticResource tabItemContent}"></TabControl>

::TabItemを生成するためのTabControlのテンプレート

<DataTemplate x:Key="tabItemContent">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <ListBox ItemTemplate="{StaticResource listBoxContent}" ItemsSource="{Binding}">
            </ListBox>
        </Grid>
    </DataTemplate>

::各TabItem内のListBoxのテンプレート

<DataTemplate x:Key="listBoxContent">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="22"/>
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Image Grid.Column="0" Source="{Binding Path=PluginIcon}" />
            <TextBlock Grid.Column="1" Text="{Binding Path=Text}" />
        </Grid>        
    </DataTemplate>

したがって、ループ内のコードでこれを実行してタブアイテムを作成しようとすると、次のようになります。

TabItem tabitem = tabControl1.Items[catIndex] as TabItem;
   tabitem.DataContext = plugins.ToList();

ここで、「プラグイン」は列挙可能です

ListBoxは制限されていません。また、TabItem内のListBoxを見つけてItemSourceプロパティを設定しようとしましたが、まったく成功しませんでした。

それ、どうやったら出来るの?

4

1 に答える 1

0

TabControlのテンプレートは、ContentPresenterを使用して、次のようにSelectedContentを表示します。

 <ContentPresenter Content="{TemplateBinding SelectedContent}"
                   ContentTemplate="{TemplateBinding ContentTemplate}" />

A ContentPresenter's job in life is to expand a DataTemplate. As it does so it sets the DataContext of the constructed visual tree to its Content property, which in this case is bound to SelectedContent.

The SelectedContent is set from the TabItem's Content property, not its DataContext. So setting the DataContext on the TabItem doesn't set the DataContext on the content area's visual tree.

What you want is:

tabItem.Content = plugins.ToList();
于 2010-06-14T07:09:28.563 に答える