【问题标题】:How can I get StackPanel to use an ItemTemplate?如何让 StackPanel 使用 ItemTemplate?
【发布时间】:2009-06-18 10:08:33
【问题描述】:

在下面的代码中,我通过分配 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>

【问题讨论】:

    标签: wpf xaml stackpanel itemtemplate


    【解决方案1】:

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

    但是,您似乎正在尝试显示单个客户而不是他们的列表(我听起来像 Clippy,不是吗?)。在这种情况下,您想使用 ContentControl:

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

    【讨论】:

    • 完美,又一个有用的控件从木制品中爬出来,谢谢
    • “看起来你正在尝试写一个值得点赞的答案”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    相关资源
    最近更新 更多