如何让StackPanel使用ItemTemplate?

14
在下面的代码中,我通过分配其ItemTemplate属性告诉ComboBox使用名为CustomerTemplate的DataTemplate。
然而,StackPanel没有ItemTemplate属性。 如何使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个回答

52

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

然而,看起来你想要显示单个客户而不是他们的列表(我听起来像Clippy,对吧?)。在这种情况下,你需要使用ContentControl:

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

2
完美,又出现了另一个有用的控件,谢谢。 - Edward Tanguay
2
似乎你想写一篇值得点赞的回答。 - Ray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接