How can I programmatically access elements defined in a ContentTemplate?

Say I created a UserControl with the following ContentTemplate defined in XAML:

<UserControl.ContentTemplate> <DataTemplate> <Ellipse Name="myEllipse" Stroke="White"/> <ContentPresenter Content="{TemplateBinding Content}"/> </DataTemplate> </UserControl.ContentTemplate> 

How can I access the myEllipse element in my code so that, for example, I can find its height using "myEllipse.Height"? I cannot access it by name directly. I tried to create a link to it with:

 Ellipse ellipse = ContentTemplate.FindName("myEllipse",this) as Ellipse; 

Failure to start the program, saying that it cannot create an instance of my class. Maybe I'm misusing FindName. If anyone can help me, it will be very grateful.

Thanks,

Dalal

+4
source share
2 answers

To use FindName on a DataTemplate, you will need a link to ContentPresenter. See Josh Smith's article How to Use FindName with ContentControl .

In fact, you can use a ControlTemplate rather than a DataTemplate. This should be easier to use and allow users of your control to use their own content templates or use implicit templates. If you do something like this:

 <UserControl.Template> <ControlTemplate TargetType="UserControl"> <Grid> <ContentPresenter/> <Ellipse Name="myEllipse" Stroke="White"/> </Grid> </ControlTemplate> </UserControl.Template> 

Then in the code (perhaps in the OverApplyTemplate override) you can do this:

 var ellipse = Template.FindName("myEllipse", this) as Ellipse; 

You should also decorate your class with the TemplatePartAttribute attribute as follows:

 [TemplatePart(Name="myEllipse", Type = typeof(Ellipse))] 

So, if someone re-earns your control, he knows to give the Ellipse element that name. (This is less important if the class is only used internally.)

Finally, if all you want to do is change the color of the ellipse, then you can just use data binding. You can create the EllipseColor dependency property on your control and simply set Stroke="{TemplateBinding EllipseColor}" .

+5
source

Try

 <Ellipse Name="myEllipse" Stroke="{TemplateBinding Background}"/> 

instead of changing it programmatically.

Here is a similar example, with a blue filled ellipse. http://msdn.microsoft.com/en-us/library/system.windows.controls.contentpresenter.aspx

0
source

All Articles