在WPF項目中,我有一個ComboBox
其中用於ItemTemplate
的DataTemplate
改變基於該ComboBoxItem
的綁定到Person
對象的IsSelected
財產Background
顏色Border
的。所以,在我的例子下面,當IsSelected=true
的Background=LightGreen
。組合框頭不尊重的ItemTemplate
當ComboBox
的下拉框打開時,這一切都很好。但是,如果在選擇Background=LightGreen
的項目後關閉下拉菜單,ComboBox
的標題不會顯示LightGreen
顏色?
任何人都可以幫助找出我需要做什麼來顯示LightGreen
顏色一旦ComboBox
關閉了IsSelected=true
項目?
非常感謝您的任何幫助。
下面是一些示例代碼來展示我的意思。
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>
後面的代碼:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Person[]
{
new Person() { Name = "Mickey" , Email= "[email protected]" , IsSelected = false},
new Person() { Name = "Donald" , Email= "[email protected]", IsSelected = true },
new Person() { Name = "Pluto" , Email= "[email protected]", IsSelected = false }
};
}
}
public class Person
{
public string Name { get; set; }
public string Email { get; set; }
public bool IsSelected { get; set; }
}
Hi @ bab7lon,謝謝你的回覆。它現在有效! – Cleve