【发布时间】:2021-01-07 08:22:53
【问题描述】:
我创建了一个 WPF UserControl 并想在另一个项目中引用它。
但是即使UserControl 可以在自己的程序集中使用,当在其他项目中引用时,会出现StaticResource not found 问题。
我的UserControl 看起来像这样:
<UserControl x:Class="DiagramDesigner.VacSymGrmV"
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:DiagramDesigner"
xmlns:s="clr-namespace:DiagramDesigner"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<local:DesignerCanvas Focusable="true" x:Name="vacgrm"
Background="{StaticResource WindowBackgroundBrush}"
Margin="10" FocusVisualStyle="{x:Null}"
ContextMenu="{StaticResource DesignerItemContextMenu}"/>
</Grid>
</UserControl>
问题点是:{Static Resource WindowBackgroundBrush},这是一个XAML文件中定义的资源:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="DisabledForegroundBrush" Color="#888" />
<SolidColorBrush x:Key="DisabledBackgroundBrush" Color="#EEE" />
<SolidColorBrush x:Key="WindowBackgroundBrush" Color="#000" />
<SolidColorBrush x:Key="SelectedBackgroundBrush" Color="#DDD" />
</ResourceDictionary>
这个程序集是一个EXE,在UserControl的设计窗口中,我可以看到它正确显示,并且编译并运行。
但是当我想在另一个 WPF 应用程序中使用 UserControl 时,就像在下面的代码中一样,这个应用程序在启动时抛出一个异常,声称找不到 WindowBackgroundBrush:
<Window x:Class="XVacSysComp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vac="clr-namespace:DiagramDesigner;assembly=VacSymDgm"
xmlns:local="clr-namespace:XVacSysComp;assembly=XVacSysComp"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<vac:VacSymGrmV>
</vac:VacSymGrmV>
</Grid>
</Window>
VacSymGrmV 是 UserControl 并且毫不奇怪,UserControl 没有正确显示在设计窗口中。
异常说:
Exception: 'WindowBackgroundBrush' is not found, 注意大写/小写...
在另一个程序集中使用静态资源时,这是与静态资源的位置有关的问题吗?
【问题讨论】:
-
该 ResourceDictionary 是否在任何地方导入,例如添加到 UserControl 的资源的MergedDictionaries 中?
-
UserControl 没有自己的资源。事实上,“
-
哦,真的,包含WindowBackgroundBrush的资源xaml出现了一些其他的资源文件。
标签: wpf xaml staticresource