My app creates a ListBox with c# code. I have managed to to set the background of my ListBox [white]. And managed to set some style attributes to the ListBoxItem (BackgroundProperty & MarginProperty).
For the MouseOver I defined a Trigger - and managed to set the BorderThicknessProperty & MarginProperty. see this article
But could not change the IsMouseOver background BackgroundProperty. I have tried to do like this:
triggerIsMouseOver.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, Brushes.Purple)); // Does not work
I have this simple XAML:
<Grid Background="Black">
<StackPanel x:Name="myStackPanel" Margin="10"></StackPanel>
</Grid>
And my code is like this:
List<string> ItemsList = new List<string>();
for (int i = 0; i < 5; i++)
{
ItemsList.Add("ListBoxItem: " + i.ToString());
}
Trigger triggerIsMouseOver = new Trigger
{
Property = ListBoxItem.IsMouseOverProperty,
Value = true
};
triggerIsMouseOver.Setters.Add(new Setter(ListBoxItem.BorderThicknessProperty, new Thickness(2)));
triggerIsMouseOver.Setters.Add(new Setter(ListBoxItem.MarginProperty, new Thickness(1)));
// Does not work
triggerIsMouseOver.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, Brushes.Purple));
Style styleListBoxItem = new Style
{
TargetType = typeof(ListBoxItem),
};
styleListBoxItem.Triggers.Add(triggerIsMouseOver);
styleListBoxItem.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, Brushes.Orange));
styleListBoxItem.Setters.Add(new Setter(ListBoxItem.MarginProperty, new Thickness(2)));
ListBox listBox = new ListBox
{
ItemsSource = ItemsList,
ItemContainerStyle = styleListBoxItem,
Background = Brushes.White
};
myStackPanel.Children.Add(listBox);

ListBox.Templateby writing a newControlTemplate. Don't use C# to create templates. You'll get no Intellisense support, since you have to write a plain string object, which is then parsed into aControlTemplateobject. Note that in order to create this string you'll have to write XAML code as well. You basically would use C# to create a string that must conform to XAML without the help of Intellisense. So you only lose when using C# to accomplish your task. Overriding the default brushes would help with aDataGridbut notListBox.