开发者

WPF - Which one is better? Style or User Control?

开发者 https://www.devze.com 2022-12-28 19:15 出处:网络
I wanted to know which one amongst Style and UserControl would be better to use in WPF? For example: I have created an image button in two different ways.

I wanted to know which one amongst Style and UserControl would be better to use in WPF?

For example: I have created an image button in two different ways. One uses Style and ContentTemplate property is set. It uses one other class with dependency properties.

The other way is I have created a UserControl which has a button and its conte开发者_Python百科nt property is set. The file UserControl.xaml.cs also contains the dependency properties.

For Code details see the answers of this question:

Custom button template in WPF

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


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

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

For example, To create a button like a play button use styles and templates, but to create a a play button which will change its appearance after pausing it use UserControl.


For this type of thing I would go with Style, even though I'm not really adept with graphical tools. I tend to produce a basic, boring style that I can get started with and then prettify it once the application functionality has been verified.

The nicest thing about WPF is being able to distance much of the graphical look, feel and behaviour away from the code.

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

There is an awkward line to tread with regards to how much behaviour is placed within the XAML and how much is placed within the code. A rough guide would be to decide on what behaviour must always be present within the UI and place that in the code, everything else place within the XAML.

Think of the code as being an abstract class with defined interfaces and the XAML Styles as being classes based on that class and you'll get an idea of what I mean.

Conversely, I know that people who are far more adept at the GUI work prefer to put more functionality in the XAML and others who prefer the code side, because they find the GUI work slow or difficult.

When thought of that way you'll see that there's never really a right or wrong answer, just better solutions that suit your skills.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号