我在 XAML 中有一个定义的路径:
<UserControl.Resources>
<ResourceDictionary>
<Path x:Key="N44" Width="20" Height="80" Stretch="Fill" Fill="#FF000000" Data="M 20,25.2941L 20,29.4118L 15.9091,29.4118L 15.9091,40L 12.2727,40L 12.2727,29.4118L 2.54313e-006,29.4118L 2.54313e-006,25.6985L 13.4872,7.62939e-006L 15.9091,7.62939e-006L 15.9091,25.2941L 20,25.2941 Z M 12.2727,25.2941L 12.2727,5.28493L 2.09517,25.2941L 12.2727,25.2941 Z M 20,65.2941L 20,69.4118L 15.9091,69.4118L 15.9091,80L 12.2727,80L 12.2727,69.4118L -5.08626e-006,69.4118L -5.08626e-006,65.6985L 13.4872,40L 15.9091,40L 15.9091,65.2941L 20,65.2941 Z M 12.2727,65.2941L 12.2727,45.2849L 2.09517,65.2941L 12.2727,65.2941 Z "/>
</ResourceDictionary>
</UserControl.Resources>
我想将它添加到 WPF 网格中并像这样工作一次:
System.Windows.Shapes.Path aPath = new System.Windows.Shapes.Path();
aPath = (System.Windows.Shapes.Path)this.Resources["N44"];
LayoutRoot.Children.Add(aPath);
但是,如果我在按钮单击事件上添加此代码,然后单击按钮两次,则会引发错误说明
“指定的视觉对象已经是另一个视觉对象的子对象或 CompositionTarget 的根。”
然后我尝试创建资源的两个实例,但我继续收到相同的错误。以下是我用于此测试的代码:
private void cmbTest_Click(object sender, System.Windows.RoutedEventArgs e)
{
System.Windows.Shapes.Path aPath = new System.Windows.Shapes.Path();
aPath = (System.Windows.Shapes.Path)this.Resources["N44"];
if (LayoutRoot.Children.Contains(aPath) == true){
System.Windows.Shapes.Path bPath = (System.Windows.Shapes.Path)this.Resources["N44"];
LayoutRoot.Children.Add(bPath);
}else{
aPath.Name = "a";
aPath.Tag = "a";
LayoutRoot.Children.Add(aPath);
}
}
因此,如何在运行时将已在 ResourceDictionary 中定义的 XAML 路径多次添加到 WPF 表单?