WPF - Which One Is Better? Style or user control?

I wanted to know which one can be used in Style and UserControl in WPF?

For example: I created an image button in two ways. One uses the Style property and ContentTemplate . It uses one other class with dependent properties.

In another way, I created a UserControl that has a button and its content property is set. The UserControl.xaml.cs file also contains dependency properties.

For code details, see the answers to this question:

Custom Button Template in WPF

Which one is better to use? In which scenario should I go for Style or UserControl or any CustomControl ?

+4
source share
2 answers

Styles are limited to setting default properties for XAML elements. For example, when I set BorderBrush, I can specify a brush, but not the width of the border. For complete freedom of appearance, use templates. To do this, create a style and specify the Template property.

Styles and templates still allow you to change the appearance of the control. To add behavior and other features, you need to create a custom control.

For example, to create a button similar to a play button, use styles and templates, but to create a play button that changes its appearance after a pause, use UserControl.

+2
source

For this type of thing, I would go with Style, although I am not very good at graphic tools. I usually create a basic, boring style with which I can start working, and then prefix it after checking the functionality of the application.

The best part about WPF is that you remove most of the graphic look, feel, and behavior away from the code.

This allows you to change the style of your application without revising the code, and also means that you can change styles on the fly at runtime.

There is an inconvenient line for the tread regarding how much the behavior is placed in XAML and how much is placed inside the code. A rough guide would be to decide what behavior should always be present in the user interface and put it in code, everything else in XAML.

Think of the code as an abstract class with specific XAML interfaces and styles as classes based on this class, and you will understand what I mean.

And vice versa, I know that people who are much better at working with the GUI prefer to add more functionality to XAML and others who prefer the code side, because they find the GUI work slow or complex.

When you think about it, you will see that there is really no right or wrong answer, just the best solutions that match your skills.

0
source

Source: https://habr.com/ru/post/1308331/


All Articles