1. 程式人生 > 其它 >WPF中的“資源”

WPF中的“資源”

WPF中的“資源”

資源概述

WPF中的資源的概念有點類似 web 技術中的靜態資源的概念。可以是一個樣式,也可以是一個button的邊框設定集合。
可以簡單的將資源分為如下幾個類別:

  • 窗體資源:顧名思義,僅可在當前窗體中使用
  • 全域性資源:相對於窗體資源而言,是一個全域性級別的,可以被多個窗體引用,可以根據不同的維度定義多個全域性資原始檔
  • 動態資源:“值”可以被改變的資源,例如:程式啟動的時候button的邊框是紅色的,當點選某個其他按鈕後,將邊框變成藍色

窗體資源

建立

  <Window.Resources>
        <SolidColorBrush x:Key="SolidColor"  Color="Red">
        </SolidColorBrush>
    </Window.Resources>

引用

使用花括號和關鍵字 StaticResource

 <StackPanel>
        <Button Content="我是一個按鈕" Margin="10"  BorderBrush="{StaticResource  SolidColor}"></Button>
 </StackPanel>

全域性資源

建立 資源字典 檔案

右鍵工程,點選新增-資源字典,命名為  DictionaryButton.xaml

編寫全域性資源

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="GlobalSolidColor" Color="Yellow"></SolidColorBrush>
    <Style x:Key="DefaultButtonStyle" TargetType="Button">
        <Setter   Property="Foreground"  Value="Blue"  ></Setter>
        <Setter   Property="FontSize"  Value="20"  ></Setter>
        <Setter  Property="BorderBrush" Value="Pink" ></Setter>
        <Setter   Property="BorderThickness"  Value="10"  ></Setter>
    </Style>
</ResourceDictionary>

引入

在 App.xaml 檔案中引入全域性資原始檔 DictionaryButton.xaml

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="DictionaryButton.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

引用

   <StackPanel>
        <Button Content="我是一個按鈕" Margin="10"   Style="{StaticResource DefaultButtonStyle}"></Button>
   </StackPanel>

動態資源

就資源本身而言,動態資源並沒有什麼特殊之處,僅僅是在處理方式上面的差異。

建立

參考 窗體資源

引用

                <StackPanel>
                    <Button Content="改變下面控制元件的邊框顏色" Margin="10"  Click="Button_Click" ></Button>
                    <Button Content="我是一個按鈕" Margin="10"  BorderBrush="{DynamicResource  SolidColor}" BorderThickness="10"></Button>
                </StackPanel>

動態編輯資源

   private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Resources["SolidColor"] = new SolidColorBrush(Colors.Blue);
        }

程式碼

https://github.com/Naylor55/WPF-Taste/tree/main/resource/ResourceTaste