user3530012
user3530012

Reputation: 740

How to dynamically change a ControlTemplate in WPF

I'm trying to create a custom control which inherits from Button. In the ControlTemplate I want to display MyCustomButton as a shape like Circle, Square or any thing else.

I have a DependencyProperty - ButtonShape - which is an enumeration type and indicates the type of the shape of the button. when the user change the ButtonShape, the appearance of the button must be changed.

I know how to create a ControlTemplate for my custom button so that it could look like a circle or square or ellipse or any other shape, but I don't know what to do with the changing part.

Maybe I should create other ControlTemplates and in the OnButtenShapeChanged event set the appropriate template but I think it is not a proper way.

Any ideas would be appreciated. Thanks.

Upvotes: 0

Views: 623

Answers (2)

Nathan A
Nathan A

Reputation: 11339

I'd override the ControlTemplate property metadata and add a Coerce callback. Then, during the Coerce phase, return the current ControlTemplate you want to use (based on your property).

On your ButtonShape property value changed callback, you'll need to call CoerceValue() to update ControlTemplate.

This will disable the consumer's ability to set their own Control Template, but it sounds like that may not be an issue here.

Here's some basics on Dependency Property Coercion: http://msdn.microsoft.com/en-us/library/ms745795(v=vs.110).aspx#Coerce_Value_Callbacks_and_Property_Changed_Events

Upvotes: 0

Adi Lester
Adi Lester

Reputation: 25211

I believe the easiest way to do so would be to define triggers in your ControlTemplate. You'll need to define the three shapes in your (single) ControlTemplate and show/hide the required shapes according to the state of the ButtonShape property.

Upvotes: 1

Related Questions