开发者

How to add content control to a shape added to a canvas all runtime

I have a static canvas. I have added a shape runtime. Then I try to add a contentcontrol which will hold the shape. But as开发者_StackOverflow the the shape is already added to the canvas, it gives a logical child error. Can anyone help me how to get this done keeping the logic of adding the contentcontrol later dynamically?

XAML: Inside window tag keep a blank canvas with name="cnv"

C#:

        Ellipse ee = new Ellipse();
        ee.Width = 100;
        ee.Height= 50;
        ee.Fill= Brushes.Red;
        ee.Name = "el";
        hidden.Children.Add(ee);

        ContentControl cc = new ContentControl();
        cc.BorderBrush = Brushes.Black;
        cc.Content = ee;

        cnv.Children.Add(ee);


As Kent points out an element can only have one parent, so simply remove the line:

    hidden.Children.Add(ee);

from your code as you are also calling:

    cnv.Children.Add(ee);


A UIElement can only have one parent, so you'll need to remove it from the Canvas before re-seating it elsewhere:

hidden.Children.Remove(ee);
cc.Content = ee;
cnv.Children.Add(ee);

PS. There's almost certainly a nicer, cleaner way to do whatever it is you're trying to do, rather than playing around in the visual tree like you are.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜