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

Tor*_*gen 82 wpf resources xaml

我正在编写几个需要共享资源和个人资源的WPF用户控件.

我已经找到了从单独的资源文件加载资源的语法:

<UserControl.Resources>
    <ResourceDictionary Source="ViewResources.xaml" />
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

我看过ResourceDictionary.MergedDictionaries,但这只能让我合并多个外部字典,而不是在本地定义更多资源.

我一定错过了一些微不足道的事情?

应该提到的是:我在WinForms项目中托管我的用户控件,因此在App.xaml中放置共享资源并不是一个真正的选择.

Tor*_*gen 155

我想到了.解决方案涉及MergedDictionaries,但具体必须恰到好处,如下所示:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ViewResources.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <!-- This works: -->
        <ControlTemplate x:Key="validationTemplate">
            ...
        </ControlTemplate>
        <style x:key="textBoxWithError" TargetType="{x:Type TextBox}">
            ...
        </style>
        ...
    </ResourceDictionary>
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)

也就是说,本地资源必须嵌套 ResourceDictionary标记中.所以这里的例子是不正确的.


Pre*_*gha 5

使用MergedDictionaries

我从这里得到以下示例

文件1

<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>
Run Code Online (Sandbox Code Playgroud)

文件2

   <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="TextStyle.xaml" />
        </ResourceDictionary.MergedDictionaries>
      </ResourceDictionary> 
Run Code Online (Sandbox Code Playgroud)

  • 对于任何获得“多次设置”错误的人:其他所有资源都必须位于第一个&lt;ResourceDictionary&gt;标记内。 (2认同)

Lu5*_*u55 5

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

<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>
Run Code Online (Sandbox Code Playgroud)