This question is inspired by this recent question and other situations I’ve encountered in my WPF development. How do I know whether it is enough to set a style on a control to override some default behavior vs creating a new control template?
More concretely, in the question above, the author wants to change the look of a ListBoxItem when it is selected. (See code reprinted below). Everything works, except the Background property. How is one supposed to know that they should override the Control Template for this?
<Style TargetType='{x:Type ListBoxItem}'> <Setter Property='Content' Value='{Binding Path=Name}'/> <Setter Property='Margin' Value='2'/> <Style.Triggers> <Trigger Property='IsSelected' Value='True'> <Setter Property='FontWeight' Value='Bold'/> <Setter Property='FontSize' Value='18'/> <Setter Property='Background' Value='Yellow'/> <Setter Property='Foreground' Value='Red'/> </Trigger> </Style.Triggers> </Style>
Styles can be thought of very closely to CSS styles in HTML. If all you want to do is change the basic properties of a control such as Background, Foreground or whatever properties it exposes then a Style is exactly what you need. Styles also allow you to apply triggers so for animations, a style is also sufficient.
If you’re finding you want to change the intrinsice behaviours / inner workings on a control then a control template is what you want. For example, if you want to change how a button is laid out by adding some sort of grid behaviour, then using a control template is the way forward.