Claw
Claw

Reputation: 474

How to change the control template effectively in WPF?

The subject is that I've defined a customized control bound to a DataContext. And I wished to change the control template dynamically according to the DataContext's specific property values.

There're 2 ways I've thought of,but I have no idea about which way is better.

1.Do not use the control template in a ResourceDictionary and all details of the control are defined in C# code.Use the DependencyProperty CallBack method to render the control when DataContext's property values change.

2.Define control template in the ResourceDictionary and use DataTrigger to change the 'Control.Template' property.

In my application,thousands of instances in this type would be created,so it's really unacceptable if the ControlTemplate changging is not effective.

Could you please give me some advices or better solutions?

Upvotes: 0

Views: 1013

Answers (3)

Stipo
Stipo

Reputation: 4606

Using any standard WPF technique might not be effective if it would involve a thousands of instances of complex controls. See http://msdn.microsoft.com/en-us/magazine/dd483292.aspx.

I would go with MultiBinding + IMultiValueConverter to Control.Template dependency property, since Template would depend on multiple DataContext properties and would, perhaps, involve complex logic.

Upvotes: 1

Mark W
Mark W

Reputation: 811

I would use a style with the data triggers to control which template is displayed. Like this example:

<Style x:Key="Die1Face" TargetType="{x:Type Button}">
        <Setter Property="Template" Value="{StaticResource dieNone}" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=ThrowDie1[0]}" Value="1" >
                <Setter Property="Template" Value="{StaticResource dieOneA}" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=ThrowDie1[0]}" Value="2" >
                <Setter Property="Template" Value="{StaticResource dieTwoA}" />
            </DataTrigger>
    </Style.Triggers>
    </Style>

This would give the flexibility you need.

Upvotes: 0

oddparity
oddparity

Reputation: 436

Perhaps you could used a ContentPresenter in your ControlTemplate to customize parts of your control. You could provide DataTemplates for those customizable parts which are automatically applied.

Upvotes: 0

Related Questions