组件用户控件引用样式资源(二)---代码引用

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

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>

 

posted @   jeffery1010  Views(279)  Comments(0Edit  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示