There is a UserControl , it has Width , Height and Backgroung .
When using this control, it is impossible to override these values ​​through the style, why?

User Control:

 <UserControl x:Class="ExperimentsWpf.UserControl1" 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" Width="100" Height="100" d:DesignHeight="450" d:DesignWidth="800" Background="Red" mc:Ignorable="d" /> 

Using:

 <Window x:Class="ExperimentsWpf.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ExperimentsWpf"> <Window.Resources> <Style x:Key="StyleUserControl1" TargetType="{x:Type local:UserControl1}"> <Setter Property="Width" Value="10" /> <Setter Property="Height" Value="10" /> <Setter Property="Background" Value="Green" /> </Style> </Window.Resources> <Grid VerticalAlignment="Center"> <local:UserControl1 Style="{StaticResource StyleUserControl1}" /> </Grid> </Window> 

    1 answer 1

    The question is related to the order (priority) of choosing the value of the dependency property.

    The fact is that explicitly setting the value of a dependency property (in the xaml markup or in the "in-country" code is not important) has the highest priority.

    This is exactly what is observed in your code: Background="Red" - this property is set explicitly and you can only override it explicitly: <local:UserControl1 Background="Green"/> , but this, as you understand, is a wrong inflexible way.

    Correctly define the default style and set the default property values ​​in it. The style can be either put into resources or placed directly in the control layout, for example:

     <UserControl x:Class="ExperimentsWpf.UserControl1" 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" d:DesignHeight="450" d:DesignWidth="800" mc:Ignorable="d"> <UserControl.Style> <Style TargetType="UserControl"> <Setter Property="Width" Value="100"/> <Setter Property="Height" Value="100"/> <Setter Property="Background" Value="Red"/> </Style> </UserControl.Style> </UserControl> 

    After that, setting properties through the custom style, of course, works as expected.

    Documentation: Dependency Property Value Precedence