Try to keep your ItemContainerStyle
simple. If you need to mess with the Template
of the item, use ItemTemplate
or RelativeSource
bindings to achieve what you need.
To get your requirement with RelativeSource
Binding, I'd just have the ItemContainerStyle
as something like:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Background"
Value="BurlyWood" />
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
<Setter Property="VerticalContentAlignment"
Value="Stretch" />
<Style.Triggers>
<Trigger Property="IsSelected"
Value="True">
<Setter Property="Background"
Value="Tomato" />
</Trigger>
<Trigger Property="IsMouseOver"
Value="True">
<Setter Property="Background"
Value="CadetBlue" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
Now to get this Background
in the UserControl
, my UserControl
xaml would be like:
<UserControl ...
Background="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ListBoxItem}},
Path=Background}">
That's it, we're sorted.
You can get the demo of this from: Here
Update:
If you're creating the UserControl
from code-behind(not sure why you need to but anyways), Assign the Binding in code-behind too. Something like:
public UserControl CreateUserControl(string text) {
Binding binding = new Binding {
Path = new PropertyPath(BackgroundProperty),
RelativeSource = new RelativeSource() {
Mode = RelativeSourceMode.FindAncestor,
AncestorType = typeof(ListBoxItem)
}
};
var uc = new UserControl {
Content = new TextBlock {
Text = text,
FontSize = 24,
FontWeight = FontWeights.Bold,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
}
};
BindingOperations.SetBinding(uc, BackgroundProperty, binding);
return uc;
}
and the ItemContainerStyle
would remain the same as before and you should be done.
Demo for this approach: Here