Dov
Dov

Reputation: 16166

Accessing Template item in code behind a Silverlight control

I've created a custom control for use in my Silverlight application. Its template is defined in the control library's Generic.xaml. Is there any way to set properties of the items in that template from the control's .cs file?

Upvotes: 0

Views: 2131

Answers (1)

ChrisF
ChrisF

Reputation: 137148

If you call GetTemplateChild(string childName) with the name of your element as defined in the XAML, for example:

<Border x:Name="MyBorder" Background="Blue" ... />

then you can change the properties of the item. You must obviously cast the returned DependencyObject to the correct type and check it's not null - just in case:

Border myBorder = GetTemplateChild("MyBorder") as Border;
if (myBorder != null)
{
    myBorder.Backround = new SolidColorBrush(...);
}

You need to call this after OnApplyTemplate has been called.

Upvotes: 3

Related Questions