[英]Button border thickness from code behind
I am very new to wpf, and right now I am working with buttons, and so I want to change buttons border thickness, but from code behind not in XAML, and what I did was next: 我是wpf的新手,现在我正在使用按钮,因此我想更改按钮的边框粗细,但是要从XAML后面的代码中删除,接下来要做的是:
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#83D744");
btn0.Background = System.Windows.Media.Brushes.Transparent; // This is applied to button
btn0.BorderThickness = new Thickness(1); //Thickness wont apply to button I dont know why
btn0.BorderBrush = brush; //This is also applied to button
Since the default button template don't have Border property, More information you can visit: here . 由于默认按钮模板没有Border属性,因此您可以访问更多信息: here 。 So if you want a border around button you have to add your own style, Like:
因此,如果要在按钮周围添加边框,则必须添加自己的样式,例如:
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="Transparent" BorderThickness="0" Background="Transparent">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
In above code all properties like: BorderBrush
, BorderThickness
and Background
are hard coded and you can't set these property from code behind. 在上面的代码中,所有属性(例如
BorderBrush
, BorderThickness
和Background
都是硬编码的,您不能从后面的代码中设置这些属性。 if you want to do so you have to write style like: 如果要这样做,则必须编写如下样式:
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding Property=BorderBrush}" BorderThickness="{TemplateBinding Property=BorderThickness}" Background="{TemplateBinding Property=Background}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And apply this style like: 并应用如下样式:
<Grid>
<Button Name="btnNew" Style="{StaticResource ButtonStyle }" Width="200" Height="50" Click="Button_Click" />
</Grid>
After that you can change those property of Border as your wish, For example: 之后,您可以根据需要更改Border的那些属性,例如:
btnNew.Background = Brushes.Black;
btnNew.BorderThickness = new Thickness(4, 5, 7, 9);
btnNew.BorderBrush = Brushes.Red;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.