3

サンプルデータを含むリストボックスにdatatemplatateを追加しようとしていますが、dataTemplateのlistboxitemには影響がないようです。使用されるコードは次のとおりです-

<Page
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.Resources>
            <DataTemplate x:Key="test1">
                <TextBlock Background="Red">
                </TextBlock>
            </DataTemplate>
        </Grid.Resources>
        <ListBox ItemTemplate="{StaticResource test1}">
            <ListBoxItem>A</ListBoxItem>
            <ListBoxItem>B</ListBoxItem>
            <ListBoxItem>C</ListBoxItem>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"  ></StackPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Grid>
</Page>

listboxitem の背景が赤くなりません。itemcontainerstyle を使用して同様のことを達成できることはわかっていますが、ここで datatemplate が適用されない理由を知りたいです。

4

1 に答える 1

7

Binding Error 情報をオンにすると、

System.Windows.Data Error: 26 : ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='ListBoxItem'

あなたがあなたのListBoxバインドを持っていたなら、それItemSourceはコレクションへのものですList<string> MyStrings

そのような

<ListBox ItemTemplate="{StaticResource test1}"
          ItemsSource="{Binding MyStrings}">
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
</ListBox>

そしてそのDataTemplate

<DataTemplate x:Key="test1">
  <TextBlock Background="Red"
              Text="{Binding .}" />
</DataTemplate>

その後、DataTemplate適用された罰金が表示されます。

于 2013-06-15T08:28:12.110 に答える