我对 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
Run Code Online (Sandbox Code Playgroud)
小智 10
按钮的默认边框粗细为 1,因此如果将其设置为 1,则不会发生任何变化。
要查看更改,只需将其设置为不同的内容:
button.BorderThickness = new Thickness(1, 1, 1, 3);
Run Code Online (Sandbox Code Playgroud)
小智 6
由于默认的按钮模板没有 Border 属性,更多信息您可以访问:这里。因此,如果您想要按钮周围有边框,则必须添加自己的样式,例如:
<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>
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,所有属性(例如: 、BorderBrush
和BorderThickness
)Background
都是硬编码的,您无法从后面的代码中设置这些属性。如果你想这样做,你必须编写如下样式:
<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>
Run Code Online (Sandbox Code Playgroud)
并应用这种风格,例如:
<Grid>
<Button Name="btnNew" Style="{StaticResource ButtonStyle }" Width="200" Height="50" Click="Button_Click" />
</Grid>
Run Code Online (Sandbox Code Playgroud)
之后您可以根据需要更改 Border 的这些属性,例如:
btnNew.Background = Brushes.Black;
btnNew.BorderThickness = new Thickness(4, 5, 7, 9);
btnNew.BorderBrush = Brushes.Red;
Run Code Online (Sandbox Code Playgroud)