如何让StackPanel使用ItemTemplate?

Edw*_*uay 11 wpf xaml itemtemplate stackpanel

在下面的代码中,我告诉ComboBox通过分配其ItemTemplate属性来使用名为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>
Run Code Online (Sandbox Code Playgroud)

Mat*_*ton 42

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

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

<ContentControl 
    Content="{Binding SelectedCustomer}"
    ContentTemplate="{StaticResource CustomerTemplate}" />
Run Code Online (Sandbox Code Playgroud)

  • 完美,另一个有用的控件从木制品中爬出来,谢谢 (2认同)
  • “看起来你正在尝试写一个值得点赞的答案” (2认同)