【发布时间】:2019-03-07 02:36:18
【问题描述】:
我需要创建一个组合,当它的下拉关闭时将显示一个简单的文本(枚举)值。但是当用户点击下拉菜单时,它应该在组合框项目中显示一个包含更多信息的复杂数据模板。
我创建了两个数据模板,用于在关闭或打开下拉菜单时显示不同的信息。
<DataTemplate x:Key="DropDownOpenedTemplate">
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<!-- Complex template -->
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<DockPanel >
<Image Width="100" DockPanel.Dock="Left" Stretch="Uniform" Source="{Binding ImageUri}"
VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,15,0" />
<StackPanel DockPanel.Dock="Right" Orientation="Vertical">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Left" FontStyle="Italic" FontWeight="Bold" Margin="10,0,0,5"/>
<TextBlock Text="{Binding Description}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="25,0,0,0"/>
</StackPanel>
</DockPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
<DataTemplate x:Key="DropDownClosedTemplate" >
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<!-- default template -->
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Stretch" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
然后我创建了一个模板选择器,它将覆盖 SelectTemplate 方法
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
ContentPresenter presenter = (ContentPresenter)container;
FrameworkElement elemnt = container as FrameworkElement;
while (container != null)
{
container = VisualTreeHelper.GetParent(container);
if (container is ComboBoxItem)
return (DataTemplate)presenter.FindResource("DropDownOpenedTemplate"); ;
}
return (DataTemplate)presenter.FindResource("DropDownClosedTemplate");
}
此功能工作正常。但现在我需要根据使用的模板格式化样式。为简化起见,我需要在选择 dropdownclosetemplate 时组合框的背景颜色为蓝色,选择 dropdownopenedtemplate 时为黄色,并且所选项目的背景应为红色。
<ComboBox x:Name="spComboBox" Grid.Row="1"
Grid.Column="1"
Width="200"
Margin="30"
Background="Blue"
HorizontalAlignment="Center"
VerticalAlignment="Center"
ItemsSource="{Binding ModeList}"
SelectedValue="{Binding SelectedMode, Mode=TwoWay}"
ScrollViewer.CanContentScroll="False"
ItemTemplateSelector="{StaticResource ComboBoxItemTemplateSelector}">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="Background" Value="Yellow"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" Value="False">
<Setter Property="Background" Value="Blue" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
我只能看到黄色,但不能在选择dropdownopededtemplate时更改DropdowncloseTemplate的样式,并选择DropdownopedTemplate时。
任何帮助将不胜感激。
【问题讨论】: