如何让StackPanel使用ItemTemplate?

时间:2023-01-25 09:04:49

In the following code, I tell the ComboBox to use the DataTemplate called CustomerTemplate by assigning its ItemTemplate attribute.

在下面的代码中,我告诉ComboBox通过分配其ItemTemplate属性来使用名为CustomerTemplate的DataTemplate。

StackPanel, however, doesn't have an ItemTemplate attribute.

但是,StackPanel没有ItemTemplate属性。

How can I get the StackPanel to also use CustomerTemplate?

如何让StackPanel也使用CustomerTemplate?

<Window.Resources>
    <DataTemplate x:Key="CustomerTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}"/>
            <TextBlock Text=" "/>
            <TextBlock Text="{Binding LastName}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<DockPanel LastChildFill="False" Margin="10">
    <ComboBox 
        x:Name="CustomerList"
        ItemTemplate="{StaticResource CustomerTemplate}"
        HorizontalAlignment="Left"
        DockPanel.Dock="Top" 
        Width="200"
        SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
        ItemsSource="{Binding Customers}"/>

    <StackPanel DataContext="{Binding SelectedCustomer}" Orientation="Horizontal">
        <TextBlock Text="Chosen: "/>
        <TextBlock Text="{Binding LastName}"/>
    </StackPanel>

</DockPanel>

1 个解决方案

#1


36  

ItemsControl is essentially a StackPanel with an ItemTemplate. It uses a StackPanel internally.

ItemsControl本质上是一个带有ItemTemplate的StackPanel。它在内部使用StackPanel。

However, it looks like you're trying to display a single customer rather than a list of them (I sound like Clippy, don't I?). In that case you want to use a ContentControl:

但是,看起来你正试图显示一个客户而不是一个列表(我听起来像Clippy,不是吗?)。在这种情况下,您想要使用ContentControl:

<ContentControl 
    Content="{Binding SelectedCustomer}"
    ContentTemplate="{StaticResource CustomerTemplate}" />

#1


36  

ItemsControl is essentially a StackPanel with an ItemTemplate. It uses a StackPanel internally.

ItemsControl本质上是一个带有ItemTemplate的StackPanel。它在内部使用StackPanel。

However, it looks like you're trying to display a single customer rather than a list of them (I sound like Clippy, don't I?). In that case you want to use a ContentControl:

但是,看起来你正试图显示一个客户而不是一个列表(我听起来像Clippy,不是吗?)。在这种情况下,您想要使用ContentControl:

<ContentControl 
    Content="{Binding SelectedCustomer}"
    ContentTemplate="{StaticResource CustomerTemplate}" />