James Cadd
James Cadd

Reputation: 12216

Is it possible to include Xaml resources in a ControlTemplate?

I'm working on a Silverlight templated control (i.e. it derives from Control and has its look implemented as a ControlTemplate in generic.xaml) and came across the need for a ValueConverter in one of my bindings. Normally I'd just create an instance of the ValueConverter in the Resources of the control working with but I can't figure out how to do that with a ControlTemplate. I'd like to keep this implementation all in Xaml if possible, but I suppose I could override OnApplyTemplate and manually create the binding with a converter.

Upvotes: 1

Views: 428

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564731

This does work in Silverlight 3. You just need to add a resources section inside your Control Template, and add the ValueConverter to the template's resources:

<ControlTemplate TargetType="controls:MyControl">
    <Grid Margin="8,40,8,20" x:Name="peopleListContainer">        
        <Grid.Resources>
            <controls:MyValueConverter x:Key="converter" />
        </Grid.Resources>
        <!-- ....

However, ValueConverters are often misused in Control Templates. You may want to use a TypeConverter instead. Bryant Likes wrote a good article discussing the difference between ValueConverter and TypeConverter in this scenario.

Upvotes: 3

Related Questions