假设我创建了一个usercontrol,其中包含在xaml中定义的以下contenttemplate:
<UserControl.ContentTemplate>
<DataTemplate>
<Ellipse Name="myEllipse" Stroke="White"/>
<ContentPresenter Content="{TemplateBinding Content}"/>
</DataTemplate>
</UserControl.ContentTemplate>
我如何访问代码中的“myellipse”元素,以便例如,我可以用“myellipse.height”找到它的高度?我不能直呼其名。我试图创建对它的引用:
Ellipse ellipse = ContentTemplate.FindName("myEllipse",this) as Ellipse;
当我运行程序时,它崩溃了,说它不能创建我的类的实例。也许我没有正确使用findname。如果有人能帮我,我将不胜感激。
谢谢,
达拉勒
最佳答案
为了在数据模板上使用findname,您将需要对contentpresenter的引用。参见josh smith的文章How to use FindName with a ContentControl。
实际上,您可能希望使用controlTemplate而不是dataTemplate。这应该更易于使用,并允许控件的用户应用自己的内容模板或使用隐式模板。如果你这样做:
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<Grid>
<ContentPresenter/>
<Ellipse Name="myEllipse" Stroke="White"/>
</Grid>
</ControlTemplate>
</UserControl.Template>
然后在代码中(可能在onapplytemplate重写中),您将能够执行以下操作:
var ellipse = Template.FindName("myEllipse", this) as Ellipse;
您还应该使用templatepartattribute来装饰类,如下所示:
[TemplatePart(Name="myEllipse", Type = typeof(Ellipse))]
因此,如果有人重新模板您的控件,他们知道提供一个椭圆元素与该名称。(如果类仅在内部使用,则这一点不太重要。)
最后,如果您只想更改椭圆的颜色,那么您可能只想使用数据绑定。您可以在控件上创建EllipseColor依赖项属性,只需设置
Stroke="{TemplateBinding EllipseColor}"
。