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}" .
source share