断开控件与BlockUIContainer的连接

我需要在FlowDocument中临时显示一些UIElement。我将其封装在BlockUIContainer中,但是当不再需要它时,我看不到如何将其与BlockUICO​​ntainer断开连接。没有删除方法。下面的代码显示-它以异常结尾

System.InvalidOperationException:'指定的元素已经是另一个元素的逻辑子级。首先断开连接。'

例如

<Grid x:Name="Grid1">
  <RichTextBox x:Name="rtb"/>
</Grid>

public MainWindow() {
    InitializeComponent();

    Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object sender,RoutedEventArgs e) {
    var c2 = new WrapPanel();
    // Imagine adding lots of controls into c2 ...
    rtb.Document.Blocks.Add(new BlockUIContainer(c2));

    var bc = (BlockUIContainer)c2.Parent;
    ((FlowDocument)(bc).Parent).Blocks.Remove(bc);

    Grid1.Children.Add(c2); // Exception. Here I want to move that c2 elsewhere in logical tree but I don't know how to disconnect it
        }

好的,我可以重新创建c2,但这不是很好。或者我看到我可以调用内部RemoveLogicalChild,但这似乎也很hacky。 WPF期望这样做如何?

谢谢

iCMS 回答:断开控件与BlockUIContainer的连接

您必须正确地从视觉树断开元素及其子元素的连接。 XAML规则不允许在树中多次引用UIElemnts。没有跟踪引用,这意味着没有单个实例的别名。每个UIElement元素必须是一个单独的实例。

您可以决定创建新实例或正确清除关联:

var c2 = new WrapPanel();

rtb.Document.Blocks.Add(new BlockUIContainer(c2));

var bc = (BlockUIContainer) c2.Parent;
rtb.Document.Blocks.Remove(bc);

// Remove parent association
bc.Child = null;

// Update the subtree/template association
c2.UpdateLayout();

Grid1.Children.Add(c2);
本文链接:https://www.f2er.com/1906157.html

大家都在问