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>
StackPanel is a layout panel that arranges child elements into a single line that can be oriented horizontally or vertically. By default, StackPanel stacks items vertically from top to bottom in the order they are declared. You can set the Orientation property to Horizontal to stack items from left to right.
You use the ItemTemplate to specify the visualization of the data objects. If your ItemsControl is bound to a collection object and you do not provide specific display instructions using a DataTemplate, the resulting UI of each item is a string representation of each object in the underlying collection.
A StackPanel allows you to stack elements in a specified direction. By using properties that are defined on StackPanel, content can flow both vertically, which is the default setting, or horizontally.
A data template can contain elements that are each bound to a data property along with additional markup that describes layout, color and other appearance. DataTemplate is, basically, used to specify the appearance of data displayed by a control not the appearance of the control itself.
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}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With