0

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?

1 Answer 1

2

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";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.