Wpf 在不同程序集中使用BasedOn样式和静态ResourceDictionary
背景 我的解决方案中有多个项目,在一个项目中,我创建了一个静态类,其中包含一个合并的Wpf 在不同程序集中使用BasedOn样式和静态ResourceDictionary,wpf,xaml,resourcedictionary,Wpf,Xaml,Resourcedictionary,背景 我的解决方案中有多个项目,在一个项目中,我创建了一个静态类,其中包含一个合并的ResourceDictionary,我在所有其他项目中使用它: namespace GUI.Shared.Resources { 公共静态类资源工厂 { 公共静态资源字典_resources=null; 公共静态资源字典资源 { 收到 { if(_resources==null) { _resources=新的ResourceDictionary(); _resources.MergedDictionaries
ResourceDictionary
,我在所有其他项目中使用它:
namespace GUI.Shared.Resources
{
公共静态类资源工厂
{
公共静态资源字典_resources=null;
公共静态资源字典资源
{
收到
{
if(_resources==null)
{
_resources=新的ResourceDictionary();
_resources.MergedDictionaries.Add(new ResourceDictionary(){Source=new Uri(“pack://application:,,,,/GUI.Shared;component/Resources/VectorIcons.xaml”)});
_resources.MergedDictionaries.Add(new ResourceDictionary(){Source=new Uri(“pack://application:,,,,/GUI.Shared;component/Resources/ButtonStyles.xaml”)});
}
返回资源;
}
}
}
}
使用xaml文件中定义的“我的样式”按钮styles.xaml:
通常我使用的样式如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/GUI.Shared;component/Resources/VectorIcons.xaml"/>
<ResourceDictionary Source="pack://application:,,,/GUI.Shared;component/Resources/ButtonStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
问题
现在我想在视图中本地扩展我的样式。我发现您是通过使用BasedOn
属性来实现这一点的
仅我的绑定方法是不允许的,给出了错误:
无法在类型为Style
的base属性上设置Binding
。只能对DependencyObject的DependencyProperty设置绑定
如何从我的ResourceFactory.Resources
中将此样式用作BasedOn
样式?该属性是常规CLR属性,而不是依赖性属性,这意味着您无法绑定它。此外,其中的索引器语法仅在Binding
标记扩展中可用,而在x:Static
、StaticResource
或DynamicResource
中不可用
您可以基于x:Static
实现创建自己的标记扩展,但这非常复杂,而且是错误的。相反,您应该考虑对您的问题采用不同的内置方法
如果你想共享资源,为什么要创建一个静态的ResourceFactory
?WPF已经通过resources
属性支持使用App.xaml
资源字典和每个FrameworkElement
中的作用域资源提供资源。为共享资源创建资源字典,例如:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/GUI.Shared;component/Resources/VectorIcons.xaml"/>
<ResourceDictionary Source="pack://application:,,,/GUI.Shared;component/Resources/ButtonStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
这里不需要绑定
,通过这种方式访问资源要容易得多。您也可以访问子控件中的资源,因为对资源的访问范围限制在它们定义的位置。谢谢!我这样做的原因是能够从我的viewmodel轻松地访问字典,比如画布上的Icon=ResourceFactory.Resources[ResourceFactory.BoxIconKey]代码>。另外,我不想在每个UserControl
中再次合并所有词典,我也不知道我可以直接加载合并后的词典。现在,我使用了一种混合方法,按照您在xaml中的建议进行操作,并在我的viewmodels中使用旧技巧。