试图有多个内容与用户控制
本文关键字:用户 控制 | 更新日期: 2023-09-27 18:07:58
下面是我为自定义用户控件编写的xaml代码。我的目标是创建一个控件,该控件在OuterBox中显示图形,但随后也将允许我使用InnerBox部分加载另一个图形以显示在其顶部。例如,第一个/底部/外部图形可以是一张狗的图片。如果用户点击此按钮并且答案正确,则会在狗的上方出现一个复选标记图形。如果答案是错误的,就会出现一个X。这是一个非常简单的例子,但说明了问题所在。我的程序将有许多外部和内部图形组合的排列,因此在资源字典中包含外部和内部图形选项的所有可能组合是不可行的。
我可以看到两个选项,第一个更可取。
-
创建控件,您可以分别设置外部和内部视图框子内容。现在,我只能做其中一个,但不能两者都做。首先设置的内容就是显示的内容。这可能吗?
-
动态生成xaml字符串,并将内部字符串拼接到外部字符串中,从而创建一个嵌套的xaml字符串。我已经验证了我可以把一个嵌套的xaml字符串到一个控件从资源字典,它将工作。为此,我如何通过代码将viewbox子内容设置为动态创建的xaml字符串,因为不可能提前存储在字典中?如果这可以工作,我可以取出两个xaml字符串(外部和内部图形),将它们拼接在一起,然后显示嵌套的图形。
我想在VB中做到这一点,但如果需要的话,将在c#中解决。
任何帮助都将非常感激。
我的控件定义。
<UserControl x:Class="CardBox"
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"
xmlns:local="clr-namespace:TestingNested"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Viewbox Name="OuterBox">
<Canvas Width="100" Height="100" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- need outer content dynamically set here -->
<Viewbox Name="InnerBox">
<!-- need inner content dynamically set here -->
</Viewbox>
</Canvas>
</Viewbox>
</UserControl>
我将使用Grid将内部图形覆盖在外部图形之上,并控制内部图形的可见性。一个Viewbox只能有一个子元素。网格可以有多个。ZIndex值高的子节点放在最上面。
<UserControl x:Class="CardBox"
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"
xmlns:local="clr-namespace:TestingNested"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid Width="100" Height="100">
<Image Source="{Binding Path=OuterGraphic}"
Panel.ZIndex="1"/>
<Image Source="{Binding Path=InnerGraphic}"
Panel.ZIndex="2"
Visibility="{Binding Path=InnerGraphicVisibility}"/>
</Grid>
</UserControl>
在你的代码后面,像这样添加OuterGraphic, InnerGraphic和InnerGraphicVisibility依赖属性:
Public Shared ReadOnly OuterGraphicProperty As DependencyProperty =
DependencyProperty.Register("OuterGraphic", GetType(ImageSource), GetType(CardBox), New PropertyMetadata(Nothing))
Public Property OuterGraphic As ImageSource
Get
Return CType(GetValue(OuterGraphicProperty), ImageSource)
End Get
Set(value As ImageSource)
SetValue(OuterGraphicProperty, value)
End Set
End Property
那么你应该能够通过设置OuterGraphic和InnerGraphic属性来动态设置图形,并通过设置InnerGraphicVisibility来打开和关闭内部图形。