1. 程式人生 > 實用技巧 >WPF -- 一種新增靜態資源的方式

WPF -- 一種新增靜態資源的方式

本文介紹使用獨立的xaml檔案新增靜態資源的方式。

步驟
  1. 建立XAML檔案,如ImageButton.xaml,新增ResourceDictionary標籤,並新增靜態資源;
  2. 在App.xaml的Application.Resources標籤中新增xaml資原始檔;
  3. 在xaml介面檔案中使用StaticResource使用靜態資源。
示例
// ImageButton.xaml
<ResourceDictionary xmlns...>
    <Style x:Key="CustomImageButton" TargetType="Button">
        ...
    </Style>
</ResourceDictionary>

// App.xaml
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/WpfApplication1;component/CustomControls/ImageButton.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

// 使用ImageButton的xaml
<StackPanel>
    <Button Width="50" Height="30" Content="Button" FontSize="14" Style="{StaticResource CustomImageButton}" />
</StackPanel>