StackPanelでItemTemplateを使用するにはどうすればよいですか?
-
06-07-2019 - |
質問
次のコードでは、 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>
解決
ItemsControl は基本的にStackPanelです。 ItemTemplate。内部でStackPanelを使用します。
ただし、顧客のリストではなく、単一の顧客を表示しようとしているようです(私はClippyのように聞こえますよね?)。その場合、ContentControlを使用します:
<ContentControl
Content="{Binding SelectedCustomer}"
ContentTemplate="{StaticResource CustomerTemplate}" />
所属していません StackOverflow