gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:34:11 32 4
gpt4 key购买 nike

我在 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com