简体   繁体   English

指定元素已经是另一个元素的逻辑子元素,当动态添加(绑定)自定义形状到面板列表框时

[英]Specified element is already the logical child of another element, when dynamically adding (binding) custom shape to listbox of panels

This InvalidOperationException with message "Specified element is already the logical child of another element, disconnect it first" is strange cause it happens when adding some 8-9 shapes, but it is logged on some previous element fi shape7, when I scroll it down, or when elements are not so much when I scroll a few upside, after scrolling downwards.这个 InvalidOperationException 带有消息“指定元素已经是另一个元素的逻辑子元素,请先断开它”很奇怪,因为它在添加一些 8-9 形状时发生,但是当我向下滚动它时,它记录在一些先前的元素 fi shape7 上,或者当我向下滚动后向上滚动几个元素时元素不是那么多。 Interestingly that when I just create one main Grid/StackPanel instead ListBox and add Custom Control with wrapped panel with added 1 Shape, it doesnot happen.有趣的是,当我只创建一个主 Grid/StackPanel 而不是 ListBox 并添加带有已添加 1 个形状的包装面板的自定义控件时,它不会发生。 In every case one nested stackpanel should have 1 shapecontrol (shape).在每种情况下,一个嵌套的堆栈面板都应该有 1 个 shapecontrol(形状)。 Here is Listbox xaml in MainWindow:这是主窗口中的列表框 xaml:

  <ListBox Height="500" ItemsSource="{Binding MyShapes}" Name = "shapeList" ScrollViewer.VerticalScrollBarVisibility="Visible"                   
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <local:ShapeControl Height="auto" Width="auto" NestedShape="{Binding}"></local:ShapeControl>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
  </ListBox>

Simple ShapeControl xaml:简单的 ShapeControl xaml:

<UserControl x:Class="ShapesProject.UserControls.Control"
    <StackPanel >
    </StackPanel>
</UserControl>

And more complex ShapeControl codebehind: I need to pass some shape (Path/GeometryGroup) with Dedendency Property, so without constructor parameter, adding it to Panel just in Loaded event, no other way around.还有更复杂的 ShapeControl 代码隐藏:我需要传递一些带有 Dedendency 属性的形状(Path/GeometryGroup),所以没有构造函数参数,只在 Loaded 事件中将其添加到 Panel 中,别无他法。

  public partial class ShapeControl : UserControl
  {
    private static int counter=0;
    public static readonly DependencyProperty NestedShapeProperty =
    DependencyProperty.Register(
        "NestedShape",
        typeof(Shape),
        typeof(ShapeControl));

    public Shape NestedShape
    {
        get { return (Shape)GetValue(NestedShapeProperty); }
        set { SetValue(NestedShapeProperty, value); }
    }

    public ShapeControl()
    {
        InitializeComponent();
            Loaded += (sender, args) =>
            {
                if (NestedShape.Parent != null) { Trace.WriteLine("Parent +" + ((StackPanel)NestedShape.Parent).Name + " " + NestedShape.Name); } //This produce parent in exception case
                ((StackPanel)this.Content).Name = "Stack" + counter++;
                ((StackPanel)this.Content).Children.Add(NestedShape); //HERE exception happes, indeed Children count changes from 0 to 1 always
                Trace.WriteLine("Parent1 +" + ((StackPanel)NestedShape.Parent).Name + " " + NestedShape.Name);
                // Here for unknown reason Names jumps Stack0,Stack2,Stack4... When customshapes 0,1,2,3,4
            };     
    }
}

I create and add the original shapes in main Panel, and simultaneously add in mainwindow to MyShapes ObservableCollection where it is binded to ItemsSource, and Item of it is binded to ShapesControl.我在主面板中创建并添加原始形状,同时将主窗口添加到 MyShapes ObservableCollection,其中它绑定到 ItemsSource,并且它的 Item 绑定到 ShapesControl。 I clone the shape with XamlReader.Parse(XamlWriter.Save(currentShape)) so it could not be the reason, and it is confirmed when passing to the same updated usercontrol, with parameter constructor dynamically, without xaml DP, that is simply added to Containg StackPanel but not to LB.我用XamlReader.Parse(XamlWriter.Save(currentShape))克隆了形状,所以这不是原因,并且在传递给相同更新的用户控件时得到确认,动态参数构造函数,没有 xaml DP,只是添加到包含 StackPanel 但不包含 LB。 When putting content of Loaded event in try-catch the StackTrace property produces such logs:将 Loaded 事件的内容放入 try-catch 时,StackTrace 属性会生成这样的日志:

System.Windows.FrameworkElement.ChangeLogicalParent(DependencyObject newParent)
       in System.Windows.FrameworkElement.AddLogicalChild(Object child)
       in System.Windows.Controls.UIElementCollection.AddInternal(UIElement element)
       in System.Windows.Controls.UIElementCollection.Add(UIElement element)
       in ShapesHandler.UserControls.ShapeControl.<.ctor>b__0(Object sender, RoutedEventArgs args) in e:\ShapesProject\ShapesProject\UserControls\ShapeControl.xaml.cs:line 60

The new moment I have noticed after catching exception inside Loaded event (otherwise putting try block around Loaded did not catched nothing, so everything crashed) is that one, that just 2-3 last shapes stays in ListBox, of 8-9 added at the moment of exception.在 Loaded 事件中捕获异常后,我注意到的新时刻(否则在 Loaded 周围放置 try 块并没有捕获任何内容,所以一切都崩溃了)是一个,只有 2-3 个最后一个形状留在 ListBox 中,添加了 8-9 个异常的时刻。 So the first ones disappear from inside of Shape Controls that comprises ListBoxItems, as just small ShapeControl void border is visible for item, instead of border that enveloped shape, and do that for last ones.因此,第一个从包含 ListBoxItems 的形状控件内部消失,因为只有小的 ShapeControl 空白边框对项目可见,而不是包围形状的边框,并且对最后一个执行此操作。 After adding next several shapes, after exception, the exception repeats - just 2-3 last shapes stays in LB.在添加下几个形状后,异常之后,异常重复 - 只有 2-3 个最后的形状留在 LB 中。 Then I checked manually Trace.WriteLine-s and noticed, that at that case 10 shapes (wrapped in User Control) was added to ListBox, and Exception happened at Stack12-Shape6 (seven one), and shapes 8-10 was preserved, but previous have logged exceptions.然后我手动检查 Trace.WriteLine-s 并注意到,在这种情况下,10 个形状(包装在用户控件中)被添加到 ListBox,并且在 Stack12-Shape6(7 个)发生异常,并且保留了 8-10 形状,但是以前记录了异常。 So after adding 10 items to LB, the previous shape6 passed to Loaded event again.所以在LB添加了10个item之后,之前的shape6再次传递给了Loaded事件。 So I supposed it was due to size, but it happened in heigh dimension (400).所以我认为这是由于尺寸,但它发生在高度维度(400)。 But after I put Height 600/800, or deleted that tag, My UserControl in near left cell, slided down.但是在我设置高度 600/800 或删除该标签后,靠近左侧单元格的 My UserControl 向下滑动。 Indeed for ListBox of 800 height I was able to add about 20 shapes without exception so it is more of size and whole layout.事实上,对于 800 高度的 ListBox,我能够毫无例外地添加大约 20 个形状,因此它的大小和整体布局更大。 But my main Canvas in UC is slided down.但是我在UC的主要Canvas滑下来了。

Indeed I do not know if Height of ListBox is the reason of exception, as I cannot find nothing similar in the internet.事实上,我不知道 ListBox 的高度是否是异常的原因,因为我在互联网上找不到类似的东西。 But why after some created items, some previous one or ones added to Loaded event, that is virtually create new item with the already added shape.但是为什么在一些创建的项目之后,一些以前的项目添加到 Loaded 事件中,这实际上是创建具有已添加形状的新项目。 With height of 800, the Exception indeed appears, but not at 10 addition, but at 15 addition in that case, and exception provoked by Shape9, but not Shape6 for example.高度为 800 时,异常确实出现了,但不是在 10 加法,而是在 15 加法在这种情况下,并且异常由 Shape9 引发,但不是 Shape6 例如。 But as 9 Shapes get disappeared in last case from UC-wrapper (transform in small border) I do undestand that this Binding: <local:ShapeControl Height="auto" Width="auto" NestedShape="{Binding}" does not work - or NestedShape (Binded to Item itself) get lost but ItemsSource is binded to MyShapes field in MainWindow.但是随着 UC-wrapper 的最后一种情况下 9 个形状消失(在小边框中转换),我确实不明白这个 Binding: <local:ShapeControl Height="auto" Width="auto" NestedShape="{Binding}" 不起作用- 或 NestedShape(绑定到项目本身)丢失,但 ItemsSource 绑定到 MainWindow 中的 MyShapes 字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 动态创建具有样式的按钮:指定的元素已经是另一个元素的逻辑子级。 首先断开连接 - Dynamically Create button with style: Specified element is already the logical child of another element. Disconnect it first 指定的元素已经是另一个元素的逻辑子级。 首先断开连接 - Specified element is already the logical child of another element. Disconnect it first 检查指定的元素是否已经是另一个元素的逻辑子元素 - Check if specified element is already the logical child of another element 指定的元素已经是另一个元素的逻辑子元素。 首先断开它 - Specified element is already the logical child of another element. Disconnect it first “指定的元素已经是另一个元素的逻辑子元素。 首先断开连接“第二次调用窗口时出错 - “Specified element is already the logical child of another element. Disconnect it first” Error on second call of window “指定的元素已经是另一个元素的逻辑子元素。 首先断开它“我的代码中的错误,任何解决方案? - “Specified element is already the logical child of another element. Disconnect it first” error in my code, Any solution? 指定的元素已经是另一个元素的逻辑子级。 首先断开连接从用户控件打印多页 - Specified element is already the logical child of another element. Disconnect it first Printing multiple pages from user control 指定的元素已经是另一个元素的逻辑子元素。 先断开它。 在用户控制中 - Specified element is already the logical child of another element. Disconnect it first. in User Control 定义DataGridTemplateColumn.Header导致“指定的元素已经是另一个元素的逻辑子级。 首先断开连接”异常 - Defining DataGridTemplateColumn.Header is causing “Specified element is already the logical child of another element. Disconnect it first” exception 添加到集合中时出现“元素已经是另一个元素的子元素”错误 - “Element is already a child of another element” error when adding to collection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM