如何从WPF中的子项访问包含Canvas控件

时间:2014-06-25 16:46:54

标签: c# wpf

我有一个Canvas,其中包含以下XAML定义:

<Canvas Height="201" VerticalAlignment="Top"
        Name="myCanvas"
        KeyDown="KeyEvent" >
    <local:MyGlyphsElement x:Name="mge" />
    <Line Name="myLine" Stroke="Blue" StrokeThickness="2"></Line>
</Canvas>

MyGlyphsElement控件的代码隐藏文件中,如何访问myLinemyCanvas? (MyGlyphsElement源自FrameworkElement。)

我的目的是能够在运行时向myCanvas个孩子添加控件,以及操纵myLine属性,例如笔画宽度等。

编辑:

public partial class MyGlyphsElement: FrameworkElement
    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);  // Good practice.
        ...
        Canvas cp = (Canvas)this.Parent;
        // Now what? How do I access myLine?

1 个答案:

答案 0 :(得分:1)

为解析Visual Tree做一些漂亮的扩展,就像这样(这样可以通过指定的名称获取元素):

public static class DependentObjectExtensions
{
    public static IEnumerable<DependencyObject> GetChildren(this DependencyObject parent)
    {
        for (int i = 0, length = VisualTreeHelper.GetChildrenCount(parent); i < length; i++)
        {
            yield return VisualTreeHelper.GetChild(parent, i);
        }
    }

    public static T FindChild<T>(this DependencyObject parent, string name, bool drillDown = false)
        where T : FrameworkElement
    {
        if(parent != null)
        {
            var elements = parent.GetChildren().OfType<T>();
            return drillDown
                ? elements.Select(x => FindChild<T>(x, name, true)).FirstOrDefault(x => x != null)
                : elements.FirstOrDefault(x => x.Name == name);
        }
        return null;
    }
}

然后,将您的MyGlyphsElement.OnRender更改为如下所示:

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        var myLine = Parent.FindChild<Line>("myLine");
        //TODO: Do stuff with your line.
    } 

如果您需要进一步说明,请告诉我,我会根据您的反馈修改我的回复。