开发者

How can I programmatically access elements defined in a ContentTemplate?

开发者 https://www.devze.com 2023-01-09 17:01 出处:网络
Let\'s say I\'ve created a UserControl with the following ContentTemplate defined in XAML: <UserControl.ContentTemplate>

Let's say I've 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 would I access the "myEllipse" element within my code so that, for example, I could find its height with "myEllipse.Height"? I cannot access it by nam开发者_C百科e directly. I attempted to create a reference to it with:

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

It crashes when I run the program, saying it can't create an instance of my class. Perhaps I'm not using FindName correctly. If anyone can help me out it would be much appreciated.

Thanks,

Dalal


In order to use FindName on a DataTemplate, you will need a reference to the ContentPresenter. See Josh Smith's article How to use FindName with a ContentControl.

What you may actually want to do is to use a ControlTemplate rather than a DataTemplate. This should be easier to use and will let users of your control apply 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 code (perhaps in an OnApplyTemplate override) you will be able to do this:

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

You should also decorate your class with a TemplatePartAttribute like this:

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

So that if anyone re-templates your control they know to provide an Ellipse element with 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 may just want to use data binding. You could create an EllipseColor dependency property on your control and just set Stroke="{TemplateBinding EllipseColor}".


Try

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

instead of programmatically changing it.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号