【问题标题】:Change my button's template using code使用代码更改我的按钮模板
【发布时间】:2014-06-25 08:40:28
【问题描述】:

我想为我的按钮创建一个模板,我可以通过代码更改其值。

这是我的模板:

<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>

我希望能够从我的代码中更改文本和图像,做类似的事情:

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

我该怎么做?

【问题讨论】:

    标签: c# wpf xaml templates button


    【解决方案1】:

    将您的ControlTemplate 更新为:

    <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>
    

    然后您可以将Button.ContentButton.Tag 设置为具有您选择的图像和文本

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 2011-03-20
      • 1970-01-01
      • 2017-12-08
      • 2020-04-01
      相关资源
      最近更新 更多