Accessing the canvas in a Silverlight 1.1 User Control


Posted on January 30, 2008
Filed Under:   1.1 Alpha, Application, Components, User Interface, XAML |

When you create a Silverlight User Control from a piece of XAML, you expect to be able to modify the Canvas using the a standard property. After all, the control’s XAML is a Canvas.

Foo.xaml
<Canvas xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="100"
Height="100"
Background="CornflowerBlue"
>
</Canvas>

However, the Control interface doesn’t have an accessor for the Canvas. Looking at the control in the debugger, you find that the Canvas is buried down deep in the control in a non-public area.

Control Canvs

So, how do you access the Canvas?
Well, there’s a simple 3-step process.


public class Foo : Control
{
// STEP1: Save the canvas locally
private Canvas _TheCanvas;


// STEP2: Add a public property so that clients can access
// the canvas easily.
//
// Control.Canvas
public Canvas Canvas
{
get { return _TheCanvas; }
}

    public Foo()
{
// STEP3: Save the canvas as the control is being created.
System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("UserControls.Foo.xaml");
_TheCanvas = this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd()) as Canvas;
}
}

That’s it. Now you can access the canvas of your control at any time.

Comments

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name (required)

Email (required)

Website

Comments

Recently


Categories


Archives


Resources