在下面的代码中,我告诉 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>
有帮助吗?

解决方案

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

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

<ContentControl 
    Content="{Binding SelectedCustomer}"
    ContentTemplate="{StaticResource CustomerTemplate}" />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top