我正在编写几个需要共享资源和个人资源的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中放置共享资源并不是一个真正的选择.
我已经在我的WPF应用程序中创建了我想在多个xaml页面中使用的控件样式.为此,我创建了一个Resources.xaml并在那里添加了样式.
然后在我的页面中添加此代码
<Grid.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/SampleEventTask;component/Resources.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Grid.Resources>
Run Code Online (Sandbox Code Playgroud)
在两个页面上,这工作正常,但在第3页上,我收到一个编译错误,说:
添加到IDictionary的所有对象必须具有Key属性或与其关联的其他类型的键.
如果我为此添加一个键,如此ResourceDictionary x:Key ="x",那么编译错误就会发生,但是在运行应用程序时它会错误地找到样式.
我可以通过将原始(没有指定键)"ResourceDictionary"xaml从顶级Grid移动到该页面上包含的Grid中来使编译错误消失并运行应用程序.
但我不明白这里发生了什么.关于问题是什么的任何建议,我只是错过了什么或做错了什么.有没有更好的方式来分享风格?
谢谢