我正在编写几个需要共享资源和个人资源的WPF用户控件。
我已经找到了从单独的资源文件加载资源的语法:
<UserControl.Resources>
<ResourceDictionary Source="ViewResources.xaml" />
</UserControl.Resources>
但是,当我这样做时,我不能在本地添加资源,例如:
<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中放置共享资源实际上并不是一种选择。
答案 0 :(得分:149)
我明白了。解决方案涉及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>
也就是说,本地资源必须嵌套在 的ResourceDictionary标记中。因此示例here不正确。
答案 1 :(得分: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>
答案 2 :(得分:4)
我从here.
获得了以下示例File1中
<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
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="TextStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>