zoukankan      html  css  js  c++  java
  • 组件用户控件引用样式资源(二)---代码引用

    关于样式文件引用方式存在以下弊端(摘自官方)

    When you reference a ResourceDictionary in XAML, a ResourceDictionary object is created each time you reference it.  So if you have 10 custom controls in your library and merge the shared ResourceDictionaries for each control by using XAML, you create 10 identical ResourceDictionary objects.  You can avoid this by creating a static class that returns the ResourceDictionary and merging the resources in code. 

    因此,我们可以通过下面方式规避这个问题

    1. 在基础资源类库中创建资源文件夹Resources,在Resources中创建字典资源样式styles.xaml

        <LinearGradientBrush x:Key="NormalBrush" StartPoint="0,0" EndPoint="0,1">
            <GradientBrush.GradientStops>
                <GradientStopCollection>
                    <GradientStop Color="#Red" Offset="0.0"/>
                    <GradientStop Color="#Blue" Offset="1.0"/>
                </GradientStopCollection>
            </GradientBrush.GradientStops>
        </LinearGradientBrush>

    2. 在Resources中创建类

     public static class SharedDictionaryStyleManager
        {
            static ResourceDictionary _SharedStyleDictionary;
            public static ResourceDictionary SharedStyleDictionary
            {
                get
                {
                    if (_SharedStyleDictionary == null)
                    {
                        System.Uri resourceLocater = new System.Uri("/MyGlobal.Infrustructure;component/Resources/Styles.xaml", System.UriKind.Relative);
                        _SharedStyleDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater);
                    }
                    return _SharedStyleDictionary;
                }
            }
        }

    3.创建用户控件UPJAppMenuView.xaml,在构造函数前访问加载样式

      public UPJAppMenuView()
            {
                //*************************************引用全局单例样式代码******************************
                this.Resources.MergedDictionaries.Add(SharedDictionaryStyleManager.SharedStyleDictionary);
                InitializeComponent();
            }

    4. 用户控件xaml就可引用了

    <Border Width="auto" Height="auto" BorderBrush="Blue" BorderThickness="10" CornerRadius="10" >
                <Rectangle Stroke="Black" StrokeThickness="2" Fill="{StaticResource NormalBrush}"></Rectangle>       
                
            </Border>

  • 相关阅读:
    MarkDown语法总结
    HashMap
    [LeetCode] 102. Binary Tree Level Order Traversal(二叉树的中序遍历)
    [LeetCode] 287. Find the Duplicate Number(寻找重复数字)
    [LeetCode] 215. Kth Largest Element in an Array(数组里的第 k 大元素)
    [LeetCode] 39. Combination Sum(组合的和)
    [LeetCode] 49. Group Anagrams(分组相同字母异序词)
    [LeetCode] 48. Rotate Image(旋转图片)
    [LeetCode] 647. Palindromic Substrings(回文子串)
    [LeetCode] 238. Product of Array Except Self(数组除自身元素外的乘积)
  • 原文地址:https://www.cnblogs.com/jeffry/p/5694565.html
Copyright © 2011-2022 走看看