Changing color of HighlighBrushKey in XAML
- by phil
Hi,
I have the following problem.
The background color in a ListView is set LightGreen or White, whether a boolflag is true or false.
Example Screen
Window1.xaml:
<Window.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=BoolFlag}" Value="True">
<Setter Property="Background" Value="LightGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<ListView ItemsSource="{Binding Path=Personen}" SelectionMode="Single" SelectionChanged="ListViewSelectionChanged">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=Vorname}" Header="Vorname" />
<GridViewColumn DisplayMemberBinding="{Binding Path=Nachname}" Header="Nachname" />
<GridViewColumn DisplayMemberBinding="{Binding Path=Alter}" Header="Alter" />
<GridViewColumn DisplayMemberBinding="{Binding Path=BoolFlag}" Header="BoolFlag" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
Window1.xaml.cs:
public partial class Window1 : Window
{
private IList<Person> _personen = new List<Person>();
public Window1()
{
_personen.Add(new Person
{
Vorname = "Max",
Nachname = "Mustermann",
Alter = 18,
BoolFlag = false,
});
_personen.Add(new Person
{
Vorname = "Karl",
Nachname = "Mayer",
Alter = 27,
BoolFlag = true,
});
_personen.Add(new Person
{
Vorname = "Josef",
Nachname = "Huber",
Alter = 38,
BoolFlag = false,
});
DataContext = this;
InitializeComponent();
}
public IList<Person> Personen
{
get
{
return _personen;
}
}
private void ListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Person person = e.AddedItems[0] as Person;
if (person != null)
{
if (person.BoolFlag)
{
this.Resources[SystemColors.HighlightBrushKey] = Brushes.Green;
}
else
{
this.Resources[SystemColors.HighlightBrushKey] = Brushes.RoyalBlue;
}
}
}
}
Person.cs:
public class Person
{
public string Vorname { get; set; }
public string Nachname { get; set; }
public int Alter { get; set; }
public bool BoolFlag { get; set; }
}
Now I want to set the highlight color of the selected item, depending on the boolflag.
In Code-Behind I do this with:
private void ListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Person person = e.AddedItems[0] as Person;
if (person != null)
{
if (person.BoolFlag)
{
this.Resources[SystemColors.HighlightBrushKey] = Brushes.Green;
}
else
{
this.Resources[SystemColors.HighlightBrushKey] = Brushes.RoyalBlue;
}
}
}
}
This works fine, but now I want to define the code above in the XAML-file.
With
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Green" />
I can overwrite the default-value. However, it works, but the color is set to Green for all selected items. I have tried different ways to switch the color of HighlightBrushKey between Green and Blue in XAML, depending on the boolflag, but I didn't succeed.
May you can help me and give me some examples?