开发者

Silverlight 4: How to access control created from codebehind

开发者 https://www.devze.com 2023-03-08 15:44 出处:网络
I\'m trying to create a method to draw a Line(path) between two UserControls. I found a post by someone 开发者_运维问答that gave me a general pointer on how to do this, I implemented the code succesfu

I'm trying to create a method to draw a Line(path) between two UserControls. I found a post by someone 开发者_运维问答that gave me a general pointer on how to do this, I implemented the code succesfully and started adapting it to my needs.

I am having a problem with accessing the user control:

Button b2 = new Button();
var transform2 = b2.TransformToVisual(b2.Parent as UIElement);

Works as it should, but my buttons get created dynamicaly through a method so I can't access them as "b2".

I tried the following:

var transfrom3 = canvas1.Children[0].TransformToVisual(canvas1.Children[0].Parent as UIElement);

but accessing it like that gives me an error on .Parent.

If have also tried:

                var p1 = this.FindName(ps.ProcessID.ToString());
                var p2 = this.FindName(ps.PreID.ToString());

                ////get geo data from both controls
                var transform1 = p1.TransformToVisual(p1.Parent as UIElement);
                var transform2 = p2.TransformToVisual(p2.Parent as UIElement);

Can anyone tell me how i can access these UserControls?


This line ought to work:-

var transfrom3 = canvas1.Children[0].TransformToVisual(canvas1.Children[0].Parent as FrameworkElement);

as you have discovered UIElement doesn't have Parent, its the FrameworkElement that adds the Parent property.

However it would be better to access the control via its name (I'll assume you are assigning a Name to the dynamically added controls).

This:-

var p1 = this.FindName(ps.ProcessID.ToString());

ought to work assuming this is UserControl and the FrameworkElement in question was given the matching name in code:-

canvas1.Children.Add(new Button() {Name = ps.ProcessID.ToString(), Content="Hello"});


Hmm I did not see that you changed UIElement to FrameworkElement, this setup works for me now:

                var control1 = this.FindName(ps.ProcessID.ToString()) as FrameworkElement;
                var control2 = this.FindName(ps.PreID.ToString()) as FrameworkElement;
                var transform1 = control1.TransformToVisual(control1.Parent as UIElement);
                var transform2 = control2.TransformToVisual(control2.Parent as UIElement);

If I add the control to a var as a FrameworkElement, then I can use the .Parent on the control again.

Thanks for your answer Anthony!

0

精彩评论

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