【问题标题】:WinRT XAML trying to use a Path defined in ResourceDictionary, but "Element is already the child of another element."WinRT XAML 尝试使用 ResourceDictionary 中定义的路径,但“元素已经是另一个元素的子元素”。
【发布时间】:2014-08-25 06:25:26
【问题描述】:

我正在使用 Visual Studio 2013 创建一个 Windows App Store 应用程序。我在一个名为AllButtonShapes.xaml 的文件中创建了一个ResourceDictionary 来存储我在按钮上使用的所有形状的路径。我在我的应用资源中添加了AllButtonShapes.xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="AllButtonShapes.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

定义的三个路径是x:Key'd 为ShapeView_NShapeView_AccIntShapeView_XPYR

我有一个名为 DynamicButton 的自定义 UserControl,它使用了 3 个路径。

<local:DynamicButton x:Name="Button_N_AccInt_XPYR" Grid.Row="1" Grid.Column="1" 
    Margin="126,82,158,56" 
    ShapeWhite="{StaticResource ShapeView_N}" 
    ShapeBlue="{StaticResource ShapeView_AccInt}" 
    ShapeOrange="{StaticResource ShapeView_XPYR}"/>

在 XAML 设计器中,我看到按钮使用这 3 个路径正确呈现。 DynamicButton xaml 使用网格 (x:Name="ShapeGrid")。在 DynamicButton 上设置三个 Shapes 之一时(通过上面显示的属性),代码将该 Shape 添加为网格的子项。

this.ShapeGrid.Children.Add(this.shapeBlue);

但是,当我运行该应用程序时,它会崩溃并出现以下错误:

“元素已经是另一个元素的子元素。”

我没有在其他任何地方使用任何形状(仍在初始测试中,所以我在屏幕上只有一个按钮)。我不知道它可能已经是什么孩子了。我调试了一下,看了this.shapeBlue.Parent,但它是空的。

a) 假设 Path 已经是另一个元素的子元素,如何从该元素中删除它以便可以使用它?

b) 是否有另一种更合适的方式来定义可重用路径,以便我可以在按钮上使用它们?

我不能只在 UserControl 中内联定义路径,因为我需要在不同的地方使用相同的 Shape。

【问题讨论】:

  • 您可以尝试this question 中的建议。我应该注意,引用的问题是针对 WPF xaml 的。我的 xaml-fu 不够好,无法告诉您它是否适用于您的具体情况。
  • 我正在尝试与其他问题不同的建议。如果他们中的任何一个成功了,我会告诉你的。

标签: c# xaml windows-runtime


【解决方案1】:

我对解决方案并不十分满意,但这就是我最终要做的:

我使用紧凑标记语法生成了所有路径:

<x:String x:Key="ShapeView_N_String">M 131.12,10.6 L 141.17,10.6 L 141.17,85.34 L 132.07,85.34 L 82.68,27.78 L 82.68,85.34 L 72.74,85.34 L 72.74,10.6 L 81.31,10.6 L 131.12,68.65 L 131.12,10.6 L 131.12,10.6</x:String>

然后在我的DynamicButton UserControl 中,我不传递形状/路径本身,而是传递字符串资源:

<local:DynamicButton
    Grid.Row="0" Grid.Column="0"
    Height="Auto" Width="Auto" 
    ShapeStringWhite="{StaticResource ShapeView_N_String}"
/>

在我的DynamicButton 类中,我有一个ShapeStringWhite 的getter/setter:

private string _shapeStringWhite;
public string ShapeStringWhite
{
    get { return this._shapeStringWhite; }

    set
    {
        this._shapeStringWhite = value;
        this.ShapeWhite = this.createPathFromString(this._shapeStringWhite);

    }
}

private Path createPathFromString(string pathMarkup)
{
    Path path = (Path)XamlReader.Load(String.Format(@"<Path xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" Data=""{0}"" />", pathMarkup));
    return path;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多