Reputation: 5444
I have a custom class ModelWorkspace
which derives from the Border
and I've used it in my XAML as below:
XAML
<workspaces:ModelWorkspace x:Name="ModelWorkspace" ClipToBounds="True">
<Canvas x:Name="ModelWindow" Width="0" Height="0">
</Canvas>
</workspaces:ModelWorkspace>
Custom Class
public class ModelWorkspace : Border
{
}
Now I want to write a constructor in this custom class and somehow access the child element of this custom class which is Canvas: ModelWindow
in this case and then add a new Canvas
to this child element.
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.
}
}
So the final result should look something like this:
<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>
Update:
<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!");
}
}
}
}
Upvotes: 1
Views: 733
Reputation: 17119
Since you have inherited from Border
, which further inherits from Decorator
, you can access the child element of your control with the Decorator.Child
property.
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.
}
Upvotes: 3