How can I get StackPanel to use an ItemTemplate?

20,152

ItemsControl is essentially a StackPanel with an ItemTemplate. It uses a StackPanel internally.

However, it looks like you're trying to display a single customer rather than a list of them (I sound like Clippy, don't I?). In that case you want to use a ContentControl:

<ContentControl 
    Content="{Binding SelectedCustomer}"
    ContentTemplate="{StaticResource CustomerTemplate}" />
Share:
20,152
Angry Dan
Author by

Angry Dan

web/software developer, .NET, C#, WPF, PHP, software trainer, English teacher, have philosophy degree, love languages, run marathons my tweets: http://www.twitter.com/edward_tanguay my runs: http://www.tanguay.info/run my code: http://www.tanguay.info/web my publications: PHP 5.3 training video (8 hours, video2brain) my projects: http://www.tanguay.info

Updated on August 03, 2020

Comments

  • Angry Dan
    Angry Dan almost 4 years

    In the following code, I tell the ComboBox to use the DataTemplate called CustomerTemplate by assigning its ItemTemplate attribute.

    StackPanel, however, doesn't have an ItemTemplate attribute.

    How can I get the StackPanel to also use 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>
    
  • Angry Dan
    Angry Dan almost 15 years
    perfect, another useful control crawled out of the woodwork, thanks
  • Syroot
    Syroot about 6 years
    "It looks like you're trying to write an upvote-worthy answer"