WPF Generate List of StackPanel with tag content "Blur"

时间:2015-12-14 18:10:33

标签: c# wpf

I need to iterate through a Grid which contains StackPanels, then I need to populate a list using location data from each StackPanel but only if that StackPanel has a tag with the content Blur.

The code I have at the moment:

 List<XYWH> MaskBlocks = new List<XYWH>();
            foreach (StackPanel gr in FindVisualChildren<StackPanel>(Container))
                if (gr.Tag.ToString() == "Blur")
                    MaskBlocks.Add(new XYWH(TransformToAncestor(gr).Transform(new Point(0, 0)), new Point(gr.ActualWidth,gr.ActualHeight)));

            MessageBox.Show(MaskBlocks.ToArray().ToString());

FindVisualChildren

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

I'm getting the following error when I attempt to add to the MaskBlocks List however.

Additional information: The specified Visual is not an ancestor of this Visual.

And the XYWH Class (basically XY Position and Width and Height):

public class XYWH
    {
        private Point _XY { get; set; }
        private Point _WH { get; set; }

        public XYWH(Point XY, Point WH)
        {
            _XY = XY;
            _WH = WH;
        }
    }

Edit:

Trying to use a Rectangle, which should be used like so: Rectangle(Point, Size), but getting the error saying "Rectangle" does not contain a constructor that takes 2 arguments.

Code:

new Rectangle(gr.TransformToAncestor(this).Transform(new Point(0, 0)), new Size(gr.ActualWidth,gr.ActualHeight))

0 个答案:

没有答案