问题描述
在以下场景中会出现一条神秘消息: 找不到资源 'styles/buttonstyles.xaml'
此消息仅在设计模式下出现,无法消除。如果我重建解决方案,错误消息就会消失,直到我打开 applicationwindow.xaml。
环境如下:
MainWindow.xaml:
...
<Grid Grid.Row="1">
<controls:CustomToolbar Style="{StaticResource ToolBarStyle}"/>
</Grid>
...
问题指向 controls:CustomToolbar 部分。
自定义工具栏.xaml:
<UserControl x:Class="Frontend.Views.Controls.CustomToolbar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Frontend.Views"
mc:Ignorable="d"
d:DesignHeight="30" d:DesignWidth="800">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,/Styles/ButtonStyles.xaml"/>
<ResourceDictionary Source="pack://application:,/Views/GlobalStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource ToolbarButton}" Command="{Binding NewProjectCommand}" ToolTip="New project">
<Image Source="{StaticResource NewProject}" Stretch="None" />
</Button>
<StackPanel Orientation="Horizontal">
<Separator Height="20" Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
</StackPanel>
</StackPanel>
</UserControl>
我尝试过的:
- google 和 stackoverflow 的每个链接
- 清理解决方案,包括删除 bin、obj、.vs 文件夹,然后重建。
- 重启 Visual Studio,重启电脑
- 使用完全限定的 URI -> 不起作用,这些字典在当前程序集中。
- 每个 ResourceDictionary 的属性都设置为 BuildAction:Page 和 MSBuild:Compile
如果我不使用任何 ResourceDictionary,则不会出现错误消息。
EDIT1:
这是项目结构: HERE
谢谢, 诺伯特
解决方法
你没有引入命名空间 where
<controls:CustomToolbar Style="{StaticResource ToolBarStyle}"/>
是程序。
将以下行添加到 Window 标记
xmlns:controls="clr-namespace:Your name space.Views.Controls"
查看CustomToolbar
所在的位置,按照上面的代码输入
看来我是通过重构mergedDictionary包含来解决这个问题的,方法如下:
- 从每个控件、样式等中删除每个 MergedDictionary。
- 将它们全部移动到 App.xaml(到根目录)
代码:
<Application x:Class="Frontend.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,/Styles/Colours.xaml" />
<ResourceDictionary Source="pack://application:,/Styles/Images.xaml" />
<ResourceDictionary Source="pack://application:,/Styles/ButtonStyles.xaml" />
<ResourceDictionary Source="pack://application:,/Styles/MenuStyles.xaml" />
<ResourceDictionary Source="pack://application:,/Styles/ToolbarStyles.xaml" />
<ResourceDictionary Source="pack://application:,/Views/GlobalStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
我非常有经验的朋友说: 如果您交换 xaml 文件中的包含顺序,则可能会发生这种情况,例如:
Style1 在 Resdic1 中定义。 Style2 在 Resdic2 中定义。 Style2 使用 Style1。
但是合并字典中的顺序如下:
- Resdic2
- Resdic1