c# - 找不到具有名称/ key 的资源

标签 c# silverlight-4.0 silverlight-toolkit

我正在尝试使用 Silverlight 4 工具包对用户界面进行单元测试。

当我尝试实例化 UserControl 时,它抛出异常,因为在 UserControl 的 XAML 中,它使用的是定义为 App.xaml 的样式。

有没有办法在我实例化 UserControl 之前以某种方式加载资源?我是不是用错了方法?

这是单元测试代码:

        [TestMethod]
    public void ExerciseTimePeriodUserInterface()
    {
        CustomUserControls.TimePeriodFilter timePeriodFilter = new CustomUserControls.TimePeriodFilter();
    }

这是对 UserControl 中样式的引用:

<Border Style="{StaticResource FilterBorderWrapper}">

最后,这是 App.xaml 中定义的样式:

    <Style TargetType="Border" x:Key="FilterBorderWrapper">
        <Setter Property="Background" Value="#F1F5FB" />
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="BorderBrush" Value="#CBD9E9" />
        <Setter Property="CornerRadius" Value="2" />
        <Setter Property="Margin" Value="2" />
    </Style>

最佳答案

如果你所有的资源都放入ResorceDictionaries。您可以简单地创建 Application 实例并将该 Dictionary 添加到资源中。请看示例:

Application _app = new Application();
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri("pack://application:,,,/Gui.Mvvm;component/Themes/YourResourceDictionary.xaml");
_app.Resources.MergedDictionaries.Add(dictionary);

对于我的 WPF 应用程序,这工作正常。编写此代码后,我可以测试我的模板选择器、数据模板选择器等。在代码隐藏调用中使用的所有代码

Application.Current.FindResource()

效果很好。

关于c# - 找不到具有名称/ key 的资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3719521/

相关文章:

windows-phone-7 - 在 Visual Studio 的 Windows Phone 7 设计 Pane 中向下滚动

c# - Visual Studio 2012 Express 调试 explorer.exe - 没有命中断点

c# - 从 Windows Phone 7 Samsung 拍摄的照片中读取经度和纬度

c# - 在MVVM中处理MouseEnter over命令

c# - MEF。如何清理默认容器?

silverlight-4.0 - Silverlight MVVM,停止 SelectionChanged 触发以响应 ItemsSource 重置

silverlight - WP7 设置日期选择器边框颜色

silverlight - 在 Silverlight 拖放中获取放置索引

c# - 如何获取在windows平台上传输和接收的字节数?

c# - 如何检测 KeyDown 事件中的 NumberDecimalSeparator (C#)