c# - 如何在运行时将已在 XAML ResourceDictionary 中定义的路径多次添加到 WPF 表单?

标签 c# wpf xaml resourcedictionary

我在 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 Gird 并像这样工作一次:

System.Windows.Shapes.Path aPath = new System.Windows.Shapes.Path();
aPath = (System.Windows.Shapes.Path)this.Resources["N44"];
LayoutRoot.Children.Add(aPath); 

但是,如果我在按钮单击事件上添加此代码,然后单击该按钮两次,则会抛出一个错误,说明

"Specified Visual is already a child of another Visual or the root of a 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 表单?

最佳答案

有一种更简单的内置方法可以做到这一点。 在资源上设置 x:Shared="False"。这将允许它被重复使用。然后根据需要多次使用它。

<UserControl.Resources>
    <ResourceDictionary>
        <Path x:Shared="False" x:Key="N44" Width="20" Height="80" Stretch="Fill" Fill="#FF000000" Data="..."/>
    </ResourceDictionary>
</UserControl.Resources>

关于c# - 如何在运行时将已在 XAML ResourceDictionary 中定义的路径多次添加到 WPF 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1377658/

相关文章:

c# - 编码的 UI 测试 - Windows - 通用应用程序

c# - 将字符串拆分(不解析)为命令行参数 C#

c# - PDF 不会自动换行并尊重行位置

wpf - 为什么文本框边框红色出现在文本框上方的面板上

c# - 基本 WPF 验证和数据绑定(bind)

xaml - Windows 10 Mobile (UWP) 上的 ContentDialog 宽度适配

c# - 如何在C#中从mysql结果中读取某些数据

c# - 您对 C# 缩小有什么建议吗?

c# - 嵌套的 xaml 元素 - 在代码中重写它

c# - TiffBitmapEncoder,内存错误导致 C#/WPF 中内存不足异常