Wpf 我将如何在userControl中嵌套其他控件?
假设我有一个名为“zoomBox”的uc,它由一些用于功能的按钮和一个用于放置嵌套内容的网格组成。如何使wpf理解网格是我希望嵌套标记所在的位置?默认情况下,我只是得到一些错误“不能在另一个某物的范围内的某物上设置name属性”。举个例子,这是uc:Wpf 我将如何在userControl中嵌套其他控件?,wpf,vb.net,xaml,Wpf,Vb.net,Xaml,假设我有一个名为“zoomBox”的uc,它由一些用于功能的按钮和一个用于放置嵌套内容的网格组成。如何使wpf理解网格是我希望嵌套标记所在的位置?默认情况下,我只是得到一些错误“不能在另一个某物的范围内的某物上设置name属性”。举个例子,这是uc: <UserControl x:Class="zoomBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
<UserControl x:Class="zoomBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid x:name="this is where nested stuff is supposed to go"/>
..some other hypothetical things
</Grid>
</UserControl>
…其他一些假设的事情
这就是我想使用它的方式
<local:zoomBox>
<StackPanel x:Name="stackPanelThatNeedsZooming!" />
</local:zoomBox>
注意:尽管使用了网格,我只对在zoomBox中添加一个子对象感兴趣
尽管使用了网格,我只对在zoomBox中添加一个子对象感兴趣
这就是a的作用
而且,由于您已经在声明UserControl的同一XAML中设置了UserControl
,请执行以下操作:
<UserControl...>
<SomeContent/>
</UserControl>
不能两次定义内容。这就是为什么你会出错
与此相反,您必须使用该控件,使其支持预定义内容和“占位符”,以便在其中放置新内容:
<UserControl x:Class="YourNamespace.zoomBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNamespace"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Template>
<ControlTemplate TargetType="{x:Type local:zoomBox}">
<Grid>
<ContentPresenter ContentSource="Content"
x:Name="This is where your nested content will go"/>
..some other hypothetical things
</Grid>
</ControlTemplate>
</UserControl.Template>
</UserControl>
…其他一些假设的事情
请注意,我添加了一个额外的xmlns
,它映射到定义zoomBox
类的CLR命名空间,以便能够定义ControlTemplate
的TargetType
详情请参阅
顺便说一句,请使用适当的命名约定,它应该是
ZoomBox
和大写的“Z”。我知道这已经超过一年了。。。我刚刚尝试了上面的XAML片段,但没有编译。我在顶部标签上得到一个编译错误,上面写着“'zoomBox'ControlTemplate TargetType与模板类型'UserControl'不匹配。如果我用{x:type local:zoomBox}替换{x:type local:zoomBox}”,那么它会编译,但不会显示内容。对此有什么想法吗?谢谢