资源在控件库中定义并从主应用程序引用时出现异常

时间:2016-12-19 23:27:26

标签: c# .net wpf xaml resourcedictionary

我的解决方案中有两个项目:主要的WPF应用程序和控件库。内部控件库有三个资源字典:Colors.xaml,Styles.xaml和Generic.xaml,内容如下:

Colors.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="MyBrush"
                     Color="Yellow" />
</ResourceDictionary>

Styles.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type TextBox}"
           x:Key="DefaultTextBox">
        <Setter Property="Background"
            Value="{StaticResource MyBrush}"></Setter>
    </Style>
</ResourceDictionary>

Generic.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Styles.xaml" />
        <ResourceDictionary Source="Color.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

现在,我想将这个Generic.xaml添加到应用程序资源中,并在主窗口中使用文本框样式,如下所示:

的App.xaml

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         x:Class="WpfApplication1.App"
         StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/ClassLibrary;component/Generic.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

MainWindow.xaml

<Window
    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"
    x:Class="WpfApplication1.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="700" Width="525">
    <TextBox Style="{StaticResource DefaultTextBox}" />
</Window>

但问题在于它会导致异常

'{DependencyProperty.UnsetValue}'不是属性'背景'的有效值

同时使用<TextBox Background="{StaticResource MyBrush}"/>可以正常工作。我该如何解决这个问题?

0 个答案:

没有答案