Question

Dans le code suivant, je dis à la ComboBox d'utiliser le DataTemplate appelé CustomerTemplate en lui attribuant son attribut ItemTemplate .

StackPanel ne possède cependant pas d'attribut ItemTemplate.

Comment faire en sorte que StackPanel utilise également 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>
Était-ce utile?

La solution

ItemsControl est essentiellement un StackPanel avec un ItemTemplate. Il utilise un StackPanel en interne.

Cependant, il semblerait que vous essayiez d'afficher un seul client plutôt qu'une liste d'entre eux (je ressemble à Clippy, n'est-ce pas?). Dans ce cas, vous souhaitez utiliser un ContentControl:

<ContentControl 
    Content="{Binding SelectedCustomer}"
    ContentTemplate="{StaticResource CustomerTemplate}" />
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top