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:
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 . 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. 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:
btnNew.Background = Brushes.Black;
btnNew.BorderThickness = new Thickness(4, 5, 7, 9);
btnNew.BorderBrush = Brushes.Red;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.