向动态按钮添加样式

时间:2017-08-18 07:50:40

标签: wpf

我已经将UI添加到这样的UI:

Button objBTN = new Button();
objBTN.Content = "Test";
grid.Children.Add(objBTN);

我怎样才能将这样的样式设置为按钮

<ControlTemplate x:Key="OrangeButtons" TargetType="{x:Type Button}">
    <Grid>
        <Border x:Name="border"   Background="White" BorderBrush="DarkGray" BorderThickness="2" CornerRadius="5,5,5,5" Width="Auto" Height="Auto">
        </Border>
        <ContentControl Content="{TemplateBinding Content}" Width="Auto" Height="Auto" VerticalAlignment="Center" HorizontalAlignment="Center"  FontSize="15"/>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="border" Property="BorderBrush" Value="Red"/>
            <Setter TargetName="border" Property="Background" Value="#FFFFC934"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

1 个答案:

答案 0 :(得分:0)

假设&#34; OrangeButtons&#34;在参考资料中声明,使用FindResource方法在代码中获取它,然后应用于按钮:

Button objBTN = new Button
{
   Content = "Test",
   Template = (ControlTemplate)grid.FindResource("OrangeButtons")
};
grid.Children.Add(objBTN);