WPF自定義控件(二)の重寫原生控件樣式模板


       

WPF控件官方樣式表 https://docs.microsoft.com/zh-cn/dotnet/framework/wpf/controls/datepicker-styles-and-templates

話外篇: 要寫一個圓形控件,用Clip,重寫模板,去除樣式引用圓形圖片可以有這三種方式。

  開發過程中,我們有時候用WPF原生的控件就能實現自己的需求,但是樣式、風格並不能滿足我們的需求,那么我們該怎么辦呢?----自定義樣式與模板。

一、樣式

在WPF中我們可以使用Style來設置控件的某些屬性值,並使該設置影響到指定范圍內的所有該類控件或影響指定的某一控件,比如說我們想將窗口中的所有按鈕都保持某一種風格,那么我們可以設置一個Style,而不必分別設置每個按鈕的風格。Style是作為一種資源被保存下來的. 看下面的例子:

            <Style x:Key="style1" TargetType="{x:Type Button}">
                <Setter Property="Background" Value="Skyblue" />
                <Setter Property="FontSize" Value="18" />
                <Setter Property="FontFamily" Value="Verdena" />
                <Setter Property="FontWeight" Value="Bold" />
            </Style>

如果我們希望是動態樣式,可以添加trigger:

      <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
        <Setter Property="Foreground" Value="Red"/>
        </Trigger>
      </Style.Triggers>

 

二、模板

ControlTemplate 指定控件的可視結構和可視行為。可以通過為控件指定新 ControlTemplate 自定義該控件的外觀。創建 ControlTemplate 后,可以在不更改現有控件的功能的情況下更改其外觀。例如,您可以將應用程序中的按鈕設置為圓形,而不是默認的方形,但該按鈕仍將引發 Click 事件。 注意: 在重定義模板前,你應該充分了解該空間的模板類型

定義模板的方法有三種:

   1.內聯定義: 

<Button Content="Button1">
  <Button.Template>
    <ControlTemplate TargetType="Button">
      <!--Define the ControlTemplate here.-->
    </ControlTemplate>
  </Button.Template>
</Button> 

2.定義為資源:
<StackPanel>
  <StackPanel.Resources>
    <ControlTemplate TargetType="Button" x:Key="newTemplate">
      <!--Define the ControlTemplate here.-->
    </ControlTemplate>
  </StackPanel.Resources>
  <Button Template="{StaticResource newTemplate}" Content="Button1"/>
</StackPanel>

3.通過Style定義:
<StackPanel>
  <StackPanel.Resources>
    <Style TargetType="Button" x:Key="newTemplate"> 
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="Button">
            <!--Define the ControlTemplate here.-->
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </StackPanel.Resources>
  <Button Style="{StaticResource newTemplate}" Content="Button1"/>
</StackPanel>

由於模板的代碼比較多,點此下載

 

自定義控件系列博文鏈接:

WPF自定義控件(一)の控件分類 
WPF自定義控件(二)の重寫原生控件樣式模板
WPF自定義控件(三)の擴展控件 
WPF自定義控件(四)の自定義控件
WPF自定義控件(五)の用戶控件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM