Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Binding in Control template

Tags:

I have the following control template.

I wish to set the source property for the image control in the control template using Template Binding.

But since this is a control template for button control and the button control doesn't have source property, i can't use TemplateBinding in this case.

<ControlTemplate x:Key="BtnTemplate" TargetType="Button">         <Border CornerRadius="5"  Margin="15" Cursor="Hand">             <StackPanel>                 <Image Name="Img" Style="{StaticResource ImageStyle}" Source="temp.jpg" Height="100" Width="100" Margin="5"></Image>                 <Label Content="{TemplateBinding Content}" Background="Transparent" Margin="2"></Label>             </StackPanel>         </Border>     </ControlTemplate> 

Since i have to set different images for different instances of button, i can't hardcode the path as well.

Please let me know how to tackle this situation.

like image 303
Sam Avatar asked Jan 09 '11 10:01

Sam


People also ask

What is TemplateBinding in XAML?

A TemplateBinding is an optimized form of a Binding for template scenarios, analogous to a Binding constructed with {Binding RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay} . A TemplateBinding is always a one-way binding, even if properties involved default to two-way binding.

What is a control template?

The ControlTemplate allows you to specify the visual structure of a control. The control author can define the default ControlTemplate and the application author can override the ControlTemplate to reconstruct the visual structure of the control.


1 Answers

I'd suggest using dynamic resources, e.g. define the template as follows:

<ControlTemplate x:Key="buttonTemplate" TargetType="Button">     <Border CornerRadius="5"  Margin="15" Cursor="Hand">         <StackPanel Orientation="Horizontal" Background="Yellow">             <Image Source="{DynamicResource ResourceKey=Img}" Height="100" Width="100" Margin="5"></Image>             <Label Content="{TemplateBinding Content}" Background="Transparent" Margin="2"></Label>         </StackPanel>     </Border> </ControlTemplate> 

And use it like this:

<Button Content="Button" Template="{StaticResource ResourceKey=buttonTemplate}">     <Button.Resources>         <ImageSource x:Key="Img">SomeUri.png/</ImageSource>     </Button.Resources> </Button> 
like image 142
H.B. Avatar answered Sep 20 '22 15:09

H.B.