user2088807
user2088807

Reputation: 1408

Change my button's template using code

I'd like to create a template for my button for which I can change the values from code.

This is my template :

<Button Name="button">
    <Button.Template>
        <ControlTemplate>
        <Border Name="bordure_bouton" >
            <Grid Name="GridPrincipale">

                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="30"/>
                </Grid.ColumnDefinitions>
                <Image Name="icone" Margin="5"  Source="icon.png" RenderOptions.BitmapScalingMode="Fant" Stretch="None" Grid.Column="1"/>
                <TextBlock Height="40" Name="label_text" FontSize="12" Text="texte" TextAlignment="Left" VerticalAlignment="Center" Grid.Column="0" Padding="12" Tag="2"/>

            </Grid>
            </Border>
        </ControlTemplate>
    </Button.Template>
</Button>

And I'd like to be able to change the text and the image from my code doing something like that :

this.icon.Source = "icon2.png";
this.label_text.Text = "text";

How can I do that?

Upvotes: 0

Views: 164

Answers (1)

Nitin Purohit
Nitin Purohit

Reputation: 18578

Update your ControlTemplate to :

<Button Name="MyButton">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Border Name="bordure_bouton" >
                        <Grid Name="GridPrincipale">

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="30"/>
                            </Grid.ColumnDefinitions>
                            <Image Name="icone" Margin="5"  Source= "{TemplateBinding Tag}" RenderOptions.BitmapScalingMode="Fant" Stretch="None" Grid.Column="0"/>
                            <TextBlock Height="40" Name="label_text" FontSize="12" Text="{TemplateBinding Content}" TextAlignment="Left" VerticalAlignment="Center" Grid.Column="1" Padding="12" Tag="2"/>

                        </Grid>
                    </Border>
                </ControlTemplate>
            </Button.Template>
        </Button>

Then you can set the Button.Content and Button.Tag to have image and text of your choice

        MyButton.Tag = new BitmapImage(new Uri(@"Icons/icon2.png", UriKind.Relative));
        MyButton.Content = "text";

Upvotes: 2

Related Questions