我正在尝试在 XAML 中为资源设置别名,如下所示:
<UserControl.Resources>
<StaticResourceExtension x:Key="newName" ResourceKey="oldName"/>
</UserControl.Resources>
oldName
简单地引用类型为 Image
的资源,定义于 App.xaml
.据我了解,这是执行此操作的正确方法,并且应该可以正常工作。但是,XAML 代码给了我一个非常无用的错误:
"The application XAML file failed to load. Fix errors in the application XAML before opening other XAML files."
当我将鼠标悬停在
StaticResourceExtension
上时会出现这种情况代码中的一行(带有波浪形下划线)。在实际的错误列表中生成了其他几个错误,但似乎相当不相关和无意义(例如“当前上下文中不存在名称‘InitializeComponent’的消息”),因为当删除该行时它们都消失了。我完全被难住了。为什么 WPF 会提示这段代码?请对决议有任何想法吗?
注意:我在 .NET 3.5 SP1 中使用 WPF。
更新 1:
我应该澄清我确实收到了编译器错误(错误列表中的上述消息),所以这不仅仅是设计者的问题。
更新 2:
这是完整的相关代码...
在 App.xaml 中(在
Application.Resource
下):<Image x:Key="bulletArrowUp" Source="Images/Icons/bullet_arrow_up.png" Stretch="None"/>
<Image x:Key="bulletArrowDown" Source="Images/Icons/bullet_arrow_down.png" Stretch="None"/>
在 MyUserControl.xaml 中(在
UserControl.Resources
下):<StaticResourceExtension x:Key="columnHeaderSortUpImage" ResourceKey="bulletArrowUp"/>
<StaticResourceExtension x:Key="columnHeaderSortDownImage" ResourceKey="bulletArrowDown"/>
当然,这些是产生错误的行。
最佳答案
尽我所能,我无法重现您的问题。我认为比您发布的代码更多。这对我来说很好用:
应用程序.xaml:
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>
<Image x:Key="bulletArrowUp" Source="Leaves.jpg" Stretch="None"/>
<Image x:Key="bulletArrowDown" Source="Leaves.jpg" Stretch="None"/>
</Application.Resources>
</Application>
Window1.xaml:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">
<local:UserControl1/>
</Window>
用户控件1.xaml:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>
<StaticResourceExtension x:Key="columnHeaderSortUpImage" ResourceKey="bulletArrowUp"/>
<StaticResourceExtension x:Key="columnHeaderSortDownImage" ResourceKey="bulletArrowDown"/>
</UserControl.Resources>
<ContentControl Content="{StaticResource columnHeaderSortUpImage}"/>
</UserControl>
我将 Leaves.jpg 图像添加到我的项目中,它显示得很好。
关于wpf - 别名资源 (WPF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1143640/