在 XAML 中获取自定义类的子元素

本文关键字:元素 自定义 XAML 获取 | 更新日期: 2023-09-27 17:58:46

我有一个自定义类ModelWorkspace它派生自Border,我已经在我的 XAML 中使用它,如下所示:

XAML

<workspaces:ModelWorkspace x:Name="ModelWorkspace" ClipToBounds="True">
    <Canvas x:Name="ModelWindow" Width="0" Height="0">
    </Canvas>                
</workspaces:ModelWorkspace>

自定义类

public class ModelWorkspace : Border
{
}

现在我想在这个自定义类中编写一个构造函数,并以某种方式访问这个自定义类的子元素,在这种情况下Canvas: ModelWindow,然后向这个子元素添加一个新Canvas

public class ModelWorkspace : Border
{
    public Canvas innerLayer { get; set; }
    public ModelWorkspace()
    {
        innerLayer = new Canvas();
        // Get the child element here and add the
        // innerLayer as its child.
    }
}

所以最终结果应该看起来像这样:

<workspaces:ModelWorkspace x:Name="ModelWorkspace" ClipToBounds="True">
    <Canvas x:Name="ModelWindow" Width="0" Height="0">
        <Canvas> // this is the inner layer we added by code.
        </Canvas>
    </Canvas>                
</workspaces:ModelWorkspace>

更新

<Window x:Class="CustomClass.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:customClass="clr-namespace:CustomClass"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <customClass:ModelWorkspace>
            <Canvas x:Name="ModelWindow" Width="0" Height="0">
            </Canvas>
        </customClass:ModelWorkspace>
    </Grid>
</Window>
using System.Windows;
using System.Windows.Controls;
namespace CustomClass
{
    public class ModelWorkspace : Border
    {
        public Canvas innerLayer { get; set; }
        public ModelWorkspace()
        {
            innerLayer = new Canvas();
            // Add "innerLayer" to the canvas defined as the child of this ModelWorkspace.
            var childCanvas = Child as Canvas;
            if (childCanvas != null)
            {
                childCanvas.Children.Add(innerLayer);
                MessageBox.Show("This worked!");
            }
        }
    }
}

在 XAML 中获取自定义类的子元素

由于您继承自 Border ,而 进一步继承自 Decorator ,因此您可以使用 Decorator.Child 属性访问控件的子元素。

public ModelWorkspace()
{
    InitializeComponent();
    innerLayer = new Canvas();
    // Add "innerLayer" to the canvas defined as the child of this ModelWorkspace.
    var childCanvas = Child as Canvas;
    if (childCanvas != null)
    {
        childCanvas.Children.Add(innerLayer);
    }
    // else the child is not a canvas.
}