zz - transcript of Defining and Using Shared Resources in a Custom Control Library

本文详细介绍了如何在WPF中定义及使用共享资源,包括在自定义控件库中通过元素级和主题级进行资源共享的方法。文章还解释了如何创建和合并资源字典,并提供了具体的XAML和代码示例。

the original link is http://blogs.msdn.com/b/wpfsdk/archive/2007/06/08/defining-and-using-shared-resources-in-a-custom-control-library.aspx


The question about how to define and use shared resources in a custom library has come up a couple times lately and after much discussion with the developer (thanks Varsha), here is the answer.

 

When an application looks for a resource, it looks at three levels in the following order:

 

  1. The element level—This is the level at which the system starts with the element that references the resource then searches resources of the logical parent and so forth until the root element is reached.
  2. The application level—Resources are defined by the Application object.
  3. The theme level-- The theme level dictionaries are stored in a subfolder called Themes.  The files in the Themes folder correspond to a theme.  For example, you might have Aero.NormalColor.xaml, Luna.NormalColor.xaml, Royale.NormalColor.xaml, etc.  You can also have a file called generic.xaml.  When the system looks for a resource at the themes level, it first looks for it in the theme-specific file and then looks for it in generic.xaml.

For more information about resources, see Resources in the WPF SDK.

 

As a control library developer, you don’t have access to the Application object, so you have to put your resources at the element level or at the theme level. 

 

Defining resources at the element level

 

You can define shared resources at the element level by creating a custom resource dictionary and merging it with your control’s resource dictionary.  When you use this method, you can call your resource file anything you want and it can be in the same folder as your controls. Resources at the element level can also use simple strings as keys. The following shared resource is defined in a file called Dictionary1.XAML (nothing new here).

 

  <LinearGradientBrush

    x:Key="myBrush" 

    StartPoint="0,0" EndPoint="1,1">

    <GradientStop Color="Red" Offset="0.25" />

    <GradientStop Color="Blue" Offset="0.75" />

  </LinearGradientBrush>

 

Once you've defined your dictionary, you need to merge it with your control's ResourceDictionary.  You can do this using XAML or code.

 

Merging the ResourceDictionary in XAML

To merge the resource dictionary using XAML, include the following in the XAML file of your custom control (in this case, a UserControl):

 

  <UserControl.Resources>

    <ResourceDictionary>

      <ResourceDictionary.MergedDictionaries>

        <ResourceDictionary Source="Dictionary1.xaml"/>

      </ResourceDictionary.MergedDictionaries>

    </ResourceDictionary>

  </UserControl.Resources>

 

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. 

 

Merging the ResourceDictionary in Code

Here is a class that returns a shared ResourceDictionary.

 

    internal static class SharedDictionaryManager

    {

        internal static ResourceDictionary SharedDictionary

        {

            get

            {

                if (_sharedDictionary == null)

                {

                    System.Uri resourceLocater =

                        newSystem.Uri("/CustomControlLibrary2;component/Dictionary1.xaml",

                                        System.UriKind.Relative);

 

                    _sharedDictionary =

                       (ResourceDictionary)Application.LoadComponent(resourceLocater);

                }

 

                return _sharedDictionary;

            }

        }

 

        private static ResourceDictionary _sharedDictionary;

    }

 

Then in the constructor of each custom control, merge the shared resource with the resources of the custom control before you call InitilizeComponent.  Because the property is static, the ResourceDictionary gets created only once.

 

this.Resources.MergedDictionaries.Add(SharedDictionaryManager.SharedDictionary);

 

Defining resources at the theme level

 

When you define a resource at the theme level, you must create a ComponentResourceKey for the resource of the key.  This isn’t too difficult, but it’s not as simple as assigning a string as the key.

 

  <LinearGradientBrush

        x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Painter},

                                 ResourceId=ButtonBrush}" 

        StartPoint="0,0" EndPoint="1,1">

    <GradientStop Color="Blue" Offset="0" />

    <GradientStop Color="White" Offset=".8" />

  </LinearGradientBrush>

 

The TypeInTargetAssembly property indicates a type that is in the same assembly as generic.xaml.  It doesn’t restrict the types within the library that can use the resource.  To use the resource in a control, simply reference it by a ComponentResourceKey:

 

    <Button  Margin="0,10,0,0" Click="FillBrush"

             Background="{StaticResource {ComponentResourceKey

                            TypeInTargetAssembly={x:Type local:Painter},

                            ResourceId=ButtonBrush}}">

      Paint ellipse

    </Button>

 

Note:  Visual Studio automatically created Themes/generic.xaml when you create a new custom control but not when you create a user control.  To use Themes/generic.xaml in a library of user controls, manually create the folder, create a new resource dictionary in that folder, and name it generic.xaml.

 

Accessing the shared resources

 

Regardless of what method you choose to create a shared dictionary, you can use the shared resources in XAML or code, just as you would any other resource.  Remember that the difference in the two is the type of the x:Key: Resources defined at the them level must be referenced by a ComponentResourceKey, while resources at the element level can be referenced by a string.

 

    <!--myBrush is a shared resource in dictionary1.xaml.-->

    <Rectangle Width="200" Height="200"

               Stroke="Black" StrokeThickness="2"

               Fill="{StaticResource myBrush}"/>

 

    <!--ButtonBrush is a resource in generic.xaml->

    <Button  Margin="0,10,0,0" Click="FillBrush"

             Background="{StaticResource {ComponentResourceKey

                            TypeInTargetAssembly={x:Type local:Painter},

                            ResourceId=ButtonBrush}}">

      Paint ellipse

    </Button>

 

To get and use resources in code, use the FindResources or TryFindResources method.  These methods are defined for FrameworkElement and FrameworkContentElement, so you can call them directly on your control.

 

            // MyEllipseBrush is a theme level resource so it has a ComponentResourceKey.

            ComponentResourceKey brushKey = newComponentResourceKey(typeof(Painter), "MyEllipseBrush");

            ellipseBrush = (Brush)this.TryFindResource(brushKey);

 

Whether you define your resources at the theme level or merge them at the element level depends on your scenario.  Here’s a summary of the things to keep in mind:

 

1)       If you create the resource dictionary at the theme level, you have to use ComponentResourceKeys as keys instead of strings. 

2)       Implicit style application does not occur on the theme level.  Suppose you want all the labels on your controls to have a certain style.  If you define the style in at the element level, you do not have to give the style an explicit key, the labels will use the style automatically.  This is not the case for resources at the theme level.  You must define a key and reference the style every place you want to use it.

3)       If you use XAML to merge resources at the element level, a ResourceDictionary is created each time you reference the shared dictionary to merge it.  To use a single instance of the shared dictionary, you have to write code.

 

The attached project defines contains two control libraries.  One library creates a ResourceDictionary in the Themes/generic.xaml file. The other library creates a shared ResourceDictionary and merges the shared dictionary with two custom controls in code. 



SharedResources.zip


内容概要:本文介绍了一个基于冠豪猪优化算法(CPO)的无人机三维路径规划项目,利用Python实现了在复杂三维环境中为无人机规划安全、高效、低能耗飞行路径的完整解决方案。项目涵盖空间环境建模、无人机动力学约束、路径编码、多目标代价函数设计以及CPO算法的核心实现。通过体素网格建模、动态障碍物处理、路径平滑技术和多约束融合机制,系统能够在高维、密集障碍环境下快速搜索出满足飞行可行性、安全性与能效最优的路径,并支持在线重规划以适应动态环境变化。文中还提供了关键模块的代码示例,包括环境建模、路径评估和CPO优化流程。; 适合人群:具备一定Python编程基础和优化算法基础知识,从事无人机、智能机器人、路径规划或智能优化算法研究的相关科研人员与工程技术人员,尤其适合研究生及有一定工作经验的研发工程师。; 使用场景及目标:①应用于复杂三维环境下的无人机自主导航与避障;②研究智能优化算法(如CPO)在路径规划中的实际部署与性能优化;③实现多目标(路径最短、能耗最低、安全性最高)耦合条件下的工程化路径求解;④构建可扩展的智能无人系统决策框架。; 阅读建议:建议结合文中模型架构与代码示例进行实践运行,重点关注目标函数设计、CPO算法改进策略与约束处理机制,宜在仿真环境中测试不同场景以深入理解算法行为与系统鲁棒性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值