如何让 StackPanel 使用 ItemTemplate?
在下面的代码中,我通过分配其 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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ItemsControl 本质上是一个带有 ItemTemplate 的 StackPanel。 它在内部使用 StackPanel。
然而,看起来您正在尝试显示单个客户而不是客户列表(我听起来像 Clippy,不是吗?)。 在这种情况下,您想使用 ContentControl:
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: