在 WPF 项目中,我有一个 ComboBox
,其中用于 ItemTemplate
的 DataTemplate
更改了 Background
颜色Border
基于 ComboBoxItem
绑定(bind)到的 Person
对象的 IsSelected
属性。因此,在我下面的示例中,当 IsSelected=true
时 Background=LightGreen
。
当 ComboBox
的下拉列表打开时,这一切都很好。但是,当下拉列表在选择带有 Background=LightGreen
的项目后关闭时,ComboBox
的标题不显示 LightGreen
颜色。
ComboBox
关闭 IsSelected=true
项目后,我需要做什么才能显示 LightGreen
颜色?
下面是一些示例代码来说明我的意思。
XAML:
<Window x:Class="combo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:combo"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ComboBox ItemsSource="{Binding .}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Border HorizontalAlignment="Stretch">
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}, Path=DataContext.IsSelected}" Value="True">
<Setter Property="Background" Value="LightGreen"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<StackPanel HorizontalAlignment="Stretch">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Email}">
</TextBlock>
</StackPanel>
</Border>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
代码隐藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Person[]
{
new Person() { Name = "Mickey" , Email= "m@disney.com" , IsSelected = false},
new Person() { Name = "Donald" , Email= "d@disney.com", IsSelected = true },
new Person() { Name = "Pluto" , Email= "p@disney.com", IsSelected = false }
};
}
}
public class Person
{
public string Name { get; set; }
public string Email { get; set; }
public bool IsSelected { get; set; }
}
最佳答案
触发器中的 RelativeSource
查找 ComboBoxItem
,您只能在弹出 的
。ItemsPresenter
中找到它>组合框
当弹出窗口关闭时,我们看到的是一个ToggleButton
和一个ContentPresenter
。
如果标记没有泄露:
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger
Binding="{Binding Path=Content.IsSelected, RelativeSource={RelativeSource
AncestorType=ContentPresenter}}" Value="True">
<Setter Property="Background" Value="LightGreen"/>
</DataTrigger>
</Style.Triggers>
</Style>
关于c# - ComboBox header 不遵守 ItemTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42561395/