我正在尝试使用 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/