簡體   English   中英

將App.xaml樣式移動到資源字典

[英]Moving App.xaml Styles to Resource Dictionary

我有一個自定義控件,它使用在app.xaml中鏈接的資源字典中的樣式。 如果我關閉該鏈接並將鏈接添加到包含該控件的頁面,則該鏈接不起作用。 這是為什么? 為什么我的控件(一個DLL)需要樣式在app.xaml中,而不僅僅是在包含控件的頁面上?

為什么我的控件(一個DLL)需要樣式在app.xaml中,而不僅僅是在包含控件的頁面上?

自定義控件需要默認樣式。 此默認樣式在構造函數中設置。 例如:

public CustomControl()
{
    DefaultStyleKey = typeof(CustomControl);
}

設置此項后,它將在此樣式的包含程序集中查找。 如果控件在應用程序中,則它在App.xaml中查找。 如果控件位於類庫中,它將在文件Generic.xaml中查找,該文件必須放在文件夾“Themes”中。 您無需將樣式放在這些文件中的任何一個中。 您可以創建一個包含該樣式的單獨文件,並從App.xaml或Themes / Generic.xaml引用它(基於定義控件的位置)。 為此,您可以在其中一個文件中創建MergedDictionary。 如果你的控件是在你的應用程序中定義的那么你可以

<Application x:Class="MyApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!--Application Resources-->
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Controls/CustomControl.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    <Application.Resources>
</Application>

如果您的控件是在類庫中定義的,則Themes / Generic.xaml應該如下所示

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/My.Custom.Assembly;component/FolderLocationOfXaml/CustomControl.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

無論您的自定義控件放在何處,xaml都將始終保持相同

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:My.Custom.Assembly.Controls">
        <Style TargetType="local:CustomControl">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:CustomControl">
                    <Grid>
                        <! -- Other stuff here -->
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

如果未定義此默認樣式,則無法確定要覆蓋的樣式。 定義默認樣式后,您可以更改應用程序中的樣式或使用控件的任何其他位置。

嘗試將樣式移動到控件中以驗證所有必需的引用是否適合您的控件使用字典中的項目。 確保包含UserControl的項目具有對包含資源字典的項目的引用。 驗證字典的源路徑:

<ResourceDictionary Source="/AssemblyName;component/StylesFolderName/ResourceDictionaryName.xaml" />

暫無
暫無

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

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