首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在WPF用户控件中组合导入资源和本地资源

如何在WPF用户控件中组合导入资源和本地资源
EN

Stack Overflow用户
提问于 2009-08-26 10:37:07
回答 2查看 53.6K关注 0票数 83

我正在编写几个既需要共享资源又需要单独资源的WPF用户控件。

我已经弄清楚了从单独的资源文件加载资源的语法:

代码语言:javascript
复制
<UserControl.Resources>
    <ResourceDictionary Source="ViewResources.xaml" />
</UserControl.Resources>

但是,当我这样做时,我不能在本地添加资源,比如:

代码语言:javascript
复制
<UserControl.Resources>
    <ResourceDictionary Source="ViewResources.xaml" />
    <!-- Doesn't work: -->
    <ControlTemplate x:Key="validationTemplate">
        ...
    </ControlTemplate>
    <style x:key="textBoxWithError" TargetType="{x:Type TextBox}">
        ...
    </style>
    ...
</UserControl.Resources>

我看过ResourceDictionary.MergedDictionaries,但它只允许我合并多个外部字典,而不是在本地定义更多的资源。

我一定漏掉了一些微不足道的东西?

值得一提的是:我在一个WinForms项目中托管我的用户控件,所以将共享资源放在App.xaml中并不是一个真正的选择。

EN

回答 2

Stack Overflow用户

发布于 2009-08-26 10:40:59

使用MergedDictionaries

我从here.获得了以下示例

File1

代码语言:javascript
复制
<ResourceDictionary 
  xmlns=" http://schemas.microsoft.com/winfx/2006/xaml/presentation "
  xmlns:x=" http://schemas.microsoft.com/winfx/2006/xaml " > 
  <Style TargetType="{x:Type TextBlock}" x:Key="TextStyle">
    <Setter Property="FontFamily" Value="Lucida Sans" />
    <Setter Property="FontSize" Value="22" />
    <Setter Property="Foreground" Value="#58290A" />
  </Style>
</ResourceDictionary>

文件2

代码语言:javascript
复制
   <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="TextStyle.xaml" />
        </ResourceDictionary.MergedDictionaries>
      </ResourceDictionary> 
票数 6
EN

Stack Overflow用户

发布于 2011-10-10 22:47:36

您可以在MergedDictionaries部分中定义本地资源:

代码语言:javascript
复制
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- import resources from external files -->
            <ResourceDictionary Source="ViewResources.xaml" />

            <ResourceDictionary>
                <!-- put local resources here -->
                <Style x:key="textBoxWithError" TargetType="{x:Type TextBox}">
                    ...
                </Style>
                ...
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1333786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档