簡體   English   中英

如何將 XAML 中定義的樣式表引用存儲在要在任何 XAML 窗口中使用的單獨類中?

[英]How to Store a stylesheet reference defined in a XAML in a separate Class to be used in any XAML Window?

我有一個 XAML MyXamlStyleSheet.xaml ,我在其中定義了按鈕和各種其他控件的樣式。 我還有一個 C# 類MyButtonClass : Button我定義它來攔截基本的 Button 類並聲明我想要給它的任何自定義功能。

在我想使用的 XAML 窗口中,我聲明了一個xmlns:lc ,源代碼指向 C# 類MyButtonClass

我想做的是當我聲明這個自定義按鈕時

<lc:MyButtonClass .../>

我有一個對存儲在MyButtonClass中的MyXamlStyleSheet中定義的樣式的引用,以便我可以從 XAML 窗口訪問它。

我會在類和 xaml 聲明中寫什么?

<lc:MyButtonClass Style="{StaticResource ???"..../>

到目前為止,我一直使用MergedDictionaries直接引用 XAML 樣式表。 但是我想使用這個不同的路徑來做到這一點。

找到了答案。 這與在Window.Resources部分將字典合並到 XAML 窗口相同。 從您的類中,您使用正確的路徑實例化一個 ResourceDictionary 並將該字典合並到 Button 類的字典中。

namespace YourNamespace
{

    public class MyCustomButton : Button
    {

        public MyCostumButton()
        {

            ResourceDictionary res = Application.LoadComponent(new Uri("/Directory/StyleDirectory.xaml", UriKind.RelativeOrAbsolute)) as ResourceDictionary;
            if (res == null)
                return;
            Resources.MergedDictionaries.Add(res);
            Style = (Style)FindResource("Name of the x:Key your gave your style");
        }
    }
}

這讓您可以在文件夾中編寫完整的標准化控件庫,其中每個控件都有一個分配給它的 C# 類。 因此,如果您有許多相同控件的實現,您始終可以定義最基本的行為並查看該類所引用的 XAML 文件。

暫無
暫無

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

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