【发布时间】:2017-03-02 16:57:07
【问题描述】:
在 WPF 项目中,我有一个 ComboBox,其中用于 ItemTemplate 的 DataTemplate 根据 Person 对象的 IsSelected 属性更改 Background 颜色ComboBoxItem 是必然的。所以,在我下面的例子中,当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; }
}
【问题讨论】: