从后面的代码按钮边框厚度

时间:2016-07-27 14:33:54

标签: c# wpf forms border styling

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

2 个答案:

答案 0 :(得分:3)

按钮的默认边框粗细为1,因此如果将其设置为1,则不会改变任何内容。

要查看更改,只需将其设置为不同的内容:

button.BorderThickness = new Thickness(1, 1, 1, 3);

enter image description here

答案 1 :(得分:2)

由于默认按钮模板没有Border属性,因此您可以访问更多信息:here。 因此,如果你想要一个边框按钮,你必须添加自己的风格,如:

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

在上面的代码中,所有属性如:BorderBrushBorderThicknessBackground都是硬编码的,您无法从后面的代码中设置这些属性。如果你想这样做,你必须写出如下样式:

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

并应用以下样式:

<Grid>
    <Button Name="btnNew" Style="{StaticResource ButtonStyle }" Width="200" Height="50" Click="Button_Click" />
</Grid>

之后,您可以根据需要更改Border的属性,例如:

btnNew.Background = Brushes.Black;
btnNew.BorderThickness = new Thickness(4, 5, 7, 9);
btnNew.BorderBrush = Brushes.Red;