簡體   English   中英

代碼后面的按鈕邊框粗細

[英]Button border thickness from code behind

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

Buttons的默認邊框粗細為1,因此如果將其設置為1,則不會改變。

要查看更改,只需將其設置為其他內容即可:

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

在此處輸入圖片說明

由於默認按鈕模板沒有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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM