如何以编程方式访问ContentTemplate中定义的元素?

时间:2010-07-29 20:12:22

标签: c# wpf user-controls

假设我已经创建了一个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。如果有人能帮助我,我将不胜感激。

谢谢,

达拉尔

2 个答案:

答案 0 :(得分:5)

要在DataTemplate上使用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))]

因此,如果有人重新模板化控件,他们就知道提供一个具有该名称的Ellipse元素。 (如果该类仅在内部使用,则这一点不太重要。)

最后,如果您只想更改Ellipse的颜色,那么您可能只想使用数据绑定。您可以在控件上创建一个EllipseColor依赖项属性,然后设置Stroke="{TemplateBinding EllipseColor}"

答案 1 :(得分:0)

尝试

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

而不是以编程方式更改它。

这里有一个类似的例子,蓝色填充椭圆。 http://msdn.microsoft.com/en-us/library/system.windows.controls.contentpresenter.aspx

相关问题