【问题标题】:Element is already the child of another element when doesnt exist?当不存在时,元素已经是另一个元素的子元素?
【发布时间】:2015-10-05 14:57:52
【问题描述】:

我正在尝试以编程方式在我的 XAML 中创建一个按钮弹出:

 <Page.Resources>
    <Button x:Key="LaunchFlyout" Content="LAUNCH">
        <Button.Flyout>
            <Flyout Placement="Top">
                <Grid Width="200" Height="200">
                    <StackPanel>
                        <Rectangle Fill="Red" Width="100" Height="100" />
                        <Rectangle Fill="Green" Width="100" Height="100" />
                    </StackPanel>
                </Grid>
            </Flyout>
        </Button.Flyout>
    </Button>
</Page.Resources>

嵌套在grids 我有:

<Grid x:Name="launchBtn_grid" Grid.Column="1">
</Grid>

然后在我的 Page_Loaded 方法中的代码中我有:

bool hasContainer = localSettings.Containers.ContainsKey("appStatus");

if (!hasContainer) {
    Button button = (Button)this.Resources["LaunchFlyout"];
    launchBtn_grid.Children.Add(button);
}
else {
    Button button = new Button();
    button.Content = "LAUNCH";
    button.Click += launch_btn_Click;
    launchBtn_grid.Children.Add(button);
}

当我调试它时,它到达 IF 语句并到达这一行 launchBtn_grid.Children.Add(button); 然后我得到这个错误 元素已经是另一个元素的子元素。

有人知道为什么吗?我已经看过了,但它们并不存在,所以我不明白为什么它会给我这个错误。有谁知道我做错了什么?

【问题讨论】:

  • 抛出异常时,button.Parent是什么?
  • @BenVoigt 它说它为空?

标签: c# windows win-universal-app


【解决方案1】:

我不确定您在什么上下文/用例中这样做,但我感觉很奇怪拥有一个实际控制作为 Resource(不是 DataTemplateStyle 等)。

如果您只想拥有 2 个不同模板的 1 个按钮,为什么不在 2 上切换 Visibility 而不是从您的代码后面加载控件?

继续这个想法,只需在 XAML 中的 Grid 中添加两个按钮,并根据您阅读的设置切换它们的 Visibility

框架中有一个BooleanToVisibilityConverter 可以帮助您解决这个问题。

【讨论】:

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