Skip to main content
 首页 » 编程设计

c#之System.Windows.ResourceReferenceKeyNotFoundException

2024年02月13日15java哥

我只在 visual studio 2010 的 XAML 编辑器中遇到异常,当我调试应用程序时一切正常并且该资源已成功加载,但是问题只发生在 XAML 编辑器中,有没有办法禁用此类异常?

    <!--ViewModels--> 
 
    <!--This View Model Causes the problem--> 
    <SharedViewModels:DatabaseViewModel x:Key="DatabaseViewModel"/> 

这就是我在主窗口中使用它的方式

DataContext="{Binding Source={StaticResource DatabaseViewModel}}" 

请您参考如下方法:

这是一个已知问题,如 Troubleshooting WPF Designer Load Failures 中所述在设计时的用户控件和自定义控件资源部分:

By default, UserControl and custom control resources that are available at run time may not be available at design time. When you add your custom controls and user controls to a Page or Window on the design surface, an instance of the control is created. Resources in App.xaml are not available to UserControl and custom control instances loaded on a page or window.

To make your resources available at design time, factor them into a separate resource dictionary and include the dictionary in App.xaml and your control's XAML. Change all StaticResource references to DynamicResource references. The following code example shows how to share a resource dictionary so that its resources are available at design time.

所以基本上除了将您的资源包含在 App.xaml 中之外,您还需要将它们包含在您的 XAML 中以使其在设计时可用。根据我的经验,使用 DynamicResource 而不是 StaticResource 似乎没有必要。