I have a MainWindow with an UserControl. I want to change the background of the ListBox which is in the UserControl. But the Style is only applied to the UserControl and not on the inner Control.
Later I want to modifiy the ListBoxItems from extern..
MainWindow
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="279.716" Width="279.784"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
</Window.Resources>
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type local:UserControl1}">
<Setter Property="Background" Value="Black"></Setter>
<Style.Resources>
<Style TargetType="{x:Type ListBox}">
<Setter Property="Background" Value="Red"></Setter>
</Style>
</Style.Resources>
</Style>
</Grid.Resources>
<local:UserControl1 Margin="47,22,34,46"></local:UserControl1>
</Grid>
XAML
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ListBox Background="Aqua" x:Name="listBox" HorizontalAlignment="Left" Height="192" Margin="54,44,0,0" VerticalAlignment="Top" Width="192"/>
</Grid>
You actually don't need a style for that. You have to bind the background property of the ListBox to the background property of the UserControl :
and the caller should look like :
And the result is :
If you want to use a style for all your custom controls for background, you should use this section of code (after you apply the suggested approach):
Now, if you want to change the background of the items it is a little bit more complicated. You have to create a style for the ListBoxItem item which should look like below :
But you probably want to control the color from outside the control, so you need a dependency property.
In UserControl1.xaml.cs you have to define :
And the style will be modified to use this property :
Now, the only thing that you have to set is this property when you use your control :
The result :