WPF整理-使用ResourceDictionary管理Logical Resources


“Logical resources may be of various types, such as brushes, geometries, styles, and templates.
Placing all those resources in a single file such as App.xaml hinders maintainability. A better
approach would be to separate resources of different types (or based on some other criteria) to
their own files. Still, they must be referenced somehow from within a common file such as App.
xaml so they are recognized.”

為了增加資源文件的可維護性,我們應該使用ResourceDictionary對資源進行:分類、匯總。

如何實現呢?舉個例子

1.新建一個WPF Application,在Application中添加一個New Item,選擇ResourceDictionary。

譬如,命名為Brushes.xaml,我們用它來存放一些筆刷。打開,我們添加一個筆刷如下:

Brushes.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <LinearGradientBrush EndPoint="1,0" x:Key="brush1">
        <GradientStop Color="Violet" Offset="0" />
        <GradientStop Color="Orange" Offset=".7" />
        <GradientStop Color="Brown" Offset="1" />
    </LinearGradientBrush>
</ResourceDictionary>

2.在App.xaml中Merge則個Resource。
“Open App.xaml. We need to merge external resource dictionaries into the main
application dictionary.

打開App.xaml,添加如下內容:

<Application x:Class="ManagingLogicalResources.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Brushes.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

3.這樣我們就可以在頁面中正常使用了。

<Window x:Class="ManagingLogicalResources.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Ellipse Fill="{StaticResource brush1}"/>
    </Grid>
</Window>

效果如下:

 -----------------------------------

在實際開發中更常用的做法是:直接在使用的View內部Merge。

<Window x:Class="WPFMergedDicitonary.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Brushes.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Ellipse Fill="{StaticResource brush1}"/>
    </Grid>
</Window>

效果同上,如下:


免責聲明!

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



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