开发者

Should I inherit from a stackpanel instead of a stack panel, grid or other UI element or UserControl?

So I'm building a peice of UI that might me in a dialog window or might be in embedded in part of a bigger page.

I don't have alot of experience with WPF, but in ASP.NET you always used UserControls, because their wasn't anyt really generic UI inherit to inherit from (and in a way UserControl was just a div).

My coworker has written alot of controls that inherit directly from stackpanel. That seems like a decent way of doing things. But when I went to create a control for the code I was going to write I was presented with a dialog that only included the UserControl, which I wasn't that familiar with in the context of WPF.

So can someone explain to me the difference from building a control that inherits from u开发者_如何学JAVAser control vs inheriting directly from a stackPanel?


There's quite a few different levels of implementing controls in WPF. According to the "WPF in Action" book, three methods can be used:

  1. User controls. This is similar to ASP.NET user controls. That you are going to build up the control with combination of other controls.
  2. Custom controls. This is intended to do more sealable and reusable components across different projects.
  3. FrameworkElement. This is even more low-level stuff.

Implementing from Stackpanel sounds similar to Custom Controls approach. It really depends what level of control, complexity, reusability you needed in choosing among that three approaches. What in my personal experience:

User controls is easier to make, but it is very hard to reuse and not easy to apply theme to it. (you know WPF allow same control have different way of presenting - further reading: templates in WPF); custom controls (you can inherit from controls, panels, grids, other controls as well) gives power to reuse, re-theme etc.

Back to your question. The answer is, depends on what you need. If you just want something similar to usercontrol in asp.net, then usercontrol in wpf. I would not inherit from stackpanel or grid, except that I am need alternative to stackpanel or grid, leave the layout to the designer to worry about.


Inheriting from StackPanel is only a good idea if you're trying to write a variant on StackPanel.

WPF programming is a lot like HTML page design - you can use a semantic structure and take care of appearance with separate styling or you can interweave logic and styling.

Your custom controls have the responsibility of providing some behaviour and data, possibly just through binding data. Depending on the amount of work in these, it might be little more than a class identifier and a default template.

One of the most important ideas in WPF is how much you can accomplish using control and data templates to change the appearance.

I recommend studying this tutorial and the diagram in Christian Moser's article.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜