根据所有文档,当您创建非无外观控件时,您应该继承 UserControl
.但是,UserControl
是 ContentControl
的简单子(monad)类但它似乎没有向它添加任何东西,界面方面。因此,您可以使用该设计器生成的代码并将基类更改为 ContentControl
它似乎仍然工作完全一样。
那么 UserControl
的意义何在?超过 ContentControl
?
更新:
对于那些不断回答的人,Visual Studio 对待他们的方式不同,我认为情况并非如此。尝试一下!新建UserControl
在 Visual Studio 中,然后在生成的 XAML 文件中,将根标记更改为 ContentControl
.然后在关联的类文件中,将基类更改为ContentControl
或者像我在这里所做的那样简单地删除它(请参阅注释),您会看到它的工作方式完全相同,包括完整的所见即所得设计器支持。
Note: You can delete the base class from the code-behind because it's actually a partial class with the other 'part' of the class being created by the XAML designer via code-generation. As such, the base class will always be defined as the root element of the XAML file, so you can simply omit it in the code-behind as it's redundant.
这是更新的 XAML ......
<ContentControl x:Class="Playground.ComboTest.InlineTextEditor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock Text="Success" />
</ContentControl>
...以及相关的类文件...
namespace Playground.ComboTest {
public partial class InlineTextEditor {
public InlineTextEditor()
=> InitializeComponent();
}
}
最佳答案
当您不需要为使用者提供 ControlTemplate 时,UserControls 非常适合聚合现有控件。这意味着 UserControls 不是没有看头的 .为什么不直接使用 ContentControl,因为它可以像 UserControl 一样耦合 XAML,并且实现看起来类似于 UserControl?好吧,您必须知道几个重要的技术差异:
VisualStateManager.GoToState()
. ContentControl 要求 VisualStateGroups 位于顶层,您必须使用 VisualStateManager.GoToElementState()
调用它们. ContentControl's ControlTemplate
<ControlTemplate TargetType="ContentControl">
<ContentPresenter
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}" />
</ControlTemplate>
UserControl's ControlTemplate
<ControlTemplate TargetType="UserControl">
<Border BorderBrush="{TemplateBinding Border.BorderBrush}"
BorderThickness="{TemplateBinding Border.BorderThickness}"
Background="{TemplateBinding Panel.Background}"
Padding="{TemplateBinding Control.Padding}"
SnapToDevicePixels="True">
<ContentPresenter
HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}"
Content="{TemplateBinding ContentControl.Content}" />
</Border>
</ControlTemplate>
关于wpf - UserControl 和 ContentControl 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18781679/