我最近做了一个用户控件 ,它花了相当长的时间,因为我有自定义依赖属性等工作...
不管怎么说,这只是一堆3个控件:文本框,弹出与分层树。
现在,我意识到我可能只写一个控件模板 。 因此,什么是使用用户控件的好处 ?
我最近做了一个用户控件 ,它花了相当长的时间,因为我有自定义依赖属性等工作...
不管怎么说,这只是一堆3个控件:文本框,弹出与分层树。
现在,我意识到我可能只写一个控件模板 。 因此,什么是使用用户控件的好处 ?
There are three cases to consider here: UserControl, ControlTemplate, and custom Control. (I'm guessing a DataTemplate needs no explanation)
A custom Control is something you provide when you create base functionality of a new UI component. There are various pros and cons for this, but for example, if you want custom selection behaviour of an ItemsControl, you could best do it by subclassing Selector or MultiSelector (the wpftoolkit DataGrid does this). Also, if you want an object which would contain a new DependencyProperty, you will in most cases derive from Control.
The wpf principle contained here is the "lookless" control paradigm, or "be sure to expect someone templating your Control, or at least make it behave nicely in your own template scenario". Custom Controls are usually created with reusability in mind, often as parts of framework dlls.
A ControlTemplate is essentially a description of a replacement visual tree, and can be set either explicitly on FrameworkElements, or as a part of a Style. This is the option you should aim at when your goal is primarily to make an application and be done with it. You can do almost anything with a ControlTemplate visually, if you are able to get the bindings and triggers (and the possible containing Style itself) right. All this can be declared as a resource an reused, to give your application a common "theme".
A UserControl is a self-contained composite control, with parts individually editable in the designer, and is best used if you need to see your components and manage them in the designer. A ControlTemplate, on the other hand, will not expose its components for manipulation in the designer (although it will be visible). You usually create a UserControl for a Customer details page, or a Product display browser, or any case where you don't want to create a full-blown Control, but want detailed view with full designer support.
A special case here is if you use the MVVM pattern. Many great MVVM implementations use UserControls as Views, and ControlTemplates and Styles as resources used by those views. MVVM practice also minimizes the need for a custom Control, and has many other benefits.
(For more information on MVVM, among many others, Google for Josh Smith, Sacha Barber and Karl Shifflett's fantastic articles)
如果要添加自己的依赖属性,那么你就需要你自己的类在其上定义它们。
当你想要一个模板适用于类,这个自定义类就会从派生Control
(如UserControl
一样)。
编写自己的主要好处Control
派生类是,它可以在应用程序中有它的模板重新定义了其他使用场景,无论是由您或类型的其他用户。
有一个在使用非常小的开销UserControl
类。 事实上,如果你在Reflector.NET看它,你会发现它几乎没有任何代码。 首先, UserControl
只是重新定义一些现有依赖属性的元数据(例如制造的默认值FocusableProperty
false
)。
除非你需要立即重新定义控制的模板,你可以把它作为一个UserControl
现在和将来有需要改变它。