簡體   English   中英

如何在代碼中訪問 generic.xaml 樣式

[英]How to access generic.xaml styles in code

我一直認為 generic.xaml 樣式被合並到 Application.Current.Resources 中,但事實並非如此。

generic.xaml 樣式存儲在哪里?

它們如何在代碼中訪問? (不是 XAML)

更新:我知道在 ResourceDictionary 中訪問顯式或隱式樣式的一般 c# 語法。 這個問題僅與模板化控件的 /Themes/Generic.xaml 樣式有關。

您不能直接從 (Program Files)\Windows Kits\10\ DesignTime \CommonConfiguration\Neutral\UAP\\Generic 文件夾訪問應用程序中 generic.xaml 中的資源,它們不會復制到您的應用程序中,因此它們不會您的應用程序的一部分,您的應用程序不能將generic.xaml 中的資源直接用作通用資源字典。

Windows 運行時不使用這些物理文件(包括 generic.xaml)進行運行時查找。 這就是為什么它們專門位於DesignTime文件夾中,並且默認情況下它們不會復制到應用程序中。 相反,這些資源字典作為 Windows 運行時本身的一部分存在於內存中,並且你的應用對主題資源(或系統資源)的 XAML 資源引用在運行時在那里解析。 請參閱資源字典結構部分中的主題資源

所以如果你想使用generic.xaml中的資源。 您應該將它作為通用 ResourceDictionary 添加到您的應用程序中,然后您可以從Page.ResourcesApplication.Current.Resources訪問它。

Application.Current.FindResource(key)
    public T GetVisualChild<T>(System.Windows.DependencyObject parent, System.Func<T, bool> predicate) where T : System.Windows.Media.Visual
    {
        int numVisuals = System.Windows.Media.VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            System.Windows.DependencyObject v = (DependencyObject)System.Windows.Media.VisualTreeHelper.GetChild(parent, i);
            T child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v, predicate);
                if (child != null)
                {
                    return child;
                }
            }
            else
            {
                if (predicate(child))
                {
                    return child;
                }
            }
        }
        return null;
    }

按鈕 btnTopMost= GetVisualChild(this, v => v.Name == "btnTopMost");

“this”是您的 MainWindow 類實例。 Generic.xaml 中的“btnTopMost”定義如下 x:Name="btnTopMost"。 在 WPF 項目中,使用此代碼,您可以訪問 Generic.xaml 的控件樣式。 我想它可能對你有幫助,祝你好運。

暫無
暫無

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

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