在现代用户界面设计中,经常需要展示复杂的数据信息,如地址信息。为了提升用户体验,希望在用户需要时提供详细信息,而在不需要时则显示简洁的信息。本文将介绍如何设计一个动态显示地址信息的模板,包括地址的展开和收起状态。
首先,需要创建数据模板来控制地址的显示方式。当地址被收起时,只展示地址名称和地址类型在一行上。以下是XAML代码示例:
<DataTemplate x:Key="AddressComboCollapsed">
<StackPanel Width="150" HorizontalAlignment="Stretch">
<DockPanel HorizontalAlignment="Stretch">
<TextBlock Text="{Binding Path=AddressName}" DockPanel.Dock="Left" />
<TextBlock Text="{Binding Path=AddressType}" DockPanel.Dock="Right" HorizontalAlignment="Right" />
</DockPanel>
</StackPanel>
</DataTemplate>
当地址被展开时,希望显示完整的地址信息,并在地址第二行为空时不显示它。以下是XAML代码示例:
<DataTemplate x:Key="AddressComboExpanded">
<GroupBox BorderThickness="1" Margin="0,0,0,3" Width="Auto" HorizontalAlignment="Stretch" Header="{Binding Path=AddressType}">
<StackPanel Margin="3" HorizontalAlignment="Stretch" MinWidth="250">
<TextBlock Text="{Binding Path=AddressName}" />
<TextBlock Text="{Binding Path=AddressLine1}" Name="tbAddr1" />
<TextBlock Text="{Binding Path=AddressLine2}" Name="tbAddr2" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=City}" />
<TextBlock Text="," Padding="0,0,5,0" />
<TextBlock Text="{Binding Path=State}" Padding="0,0,5,0" />
<TextBlock Text="{Binding Path=PostalCode}" />
</StackPanel>
</StackPanel>
</GroupBox>
</DataTemplate>
接下来,需要创建一个数据模板选择器类,该类继承自 System.Windows.Controls.DataTemplateSelector
,并重写 SelectTemplate
方法。以下是C#代码示例:
public class AddressTemplateSelector : System.Windows.Controls.DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
ContentPresenter presenter = (ContentPresenter)container;
if (presenter.TemplatedParent is ComboBox)
{
return (DataTemplate)presenter.FindResource("AddressComboCollapsed");
}
else // Templated parent is ComboBoxItem
{
return (DataTemplate)presenter.FindResource("AddressComboExpanded");
}
}
}
<ComboBox Height="30" Width="200" ItemsSource="{Binding Path=Addresses}">
<ComboBox.ItemTemplateSelector>
<dt:AddressTemplateSelector />
</ComboBox.ItemTemplateSelector>
</ComboBox>