XAML用户控件基本元素类型

XAML用户控件基本元素类型,xaml,inheritance,user-controls,Xaml,Inheritance,User Controls,在XAML中,您可以创建自己的可重用控件类型作为UserControl对象,如下所示: <UserControl x:Class="MyControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid>

在XAML中,您可以创建自己的可重用控件类型作为UserControl对象,如下所示:

<UserControl x:Class="MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
            <Button Content="Test"/>
    </Grid>
</UserControl>
<Grid x:Class="MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Button Content="Test"/>
</Grid>

但您也可以将该视图中的基本类型更改为与内容容器相同的类型,如下所示:

<UserControl x:Class="MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
            <Button Content="Test"/>
    </Grid>
</UserControl>
<Grid x:Class="MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Button Content="Test"/>
</Grid>

这两个选项之间有什么区别?在我的示例中,它们都派生自
FrameworkElement
,并在继承上从那里发散。但看起来它们的功能是一样的


我相信两者之间有很好的理由,但我很难想出一个好的方案来证明这种区别。有人能给我一些启发吗?

老实说,拥有不同基类型的主要原因是属性

如果你发现UserControl没有你需要的依赖属性——也许你希望它不时地扩展一些内容,那么你可以将它建立在一个扩展器上,而不是在后面的代码中键入“propdp”并重新设计轮子,替换模板,而不只是将内容填充到“内容”中属性并绑定到扩展器的“IsExpanded”属性

这样做可以通过复制现有控件的模板并添加到其中,从而模糊UserControl和Custom控件之间的界限;利用现有属性并在需要时在代码隐藏中添加新属性

UserControl标记本身只是一个平均基数,但是如果您觉得其他东西更适合您想要的控件,那么就使用它

或者,如果您只需要一个美化的容器来lob一堆文本框或一些经常使用的内容,那么您无需更改任何内容