我为可重用控件创建了一个程序集(除其他外)。在此程序集中,有一个 Themes/Generic.xaml 文件用于自定义控件样式。我想在单独的文件中为不同的控件实现不同的样式,所以我认为使用合并字典是个好主意。
我的 Generic/Themes.xaml 看起来像这样:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Resources/MyTextBoxStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
文件 MyTextBoxStyle.xaml 如下所示:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:general="clr-namespace:com.testsoft.General">
<Style TargetType="{x:Type general:MyTextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="IsReadOnly" Value="True" />
<Setter Property="Foreground" Value="Black" />
<Style.Triggers>
<Trigger Property="IsReadOnly" Value="True">
<Setter Property="Foreground" Value="Gray" />
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
我添加了一个静态构造函数,因此将应用样式:
static MyTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(typeof(MyTextBox)));
}
在另一个程序集中使用此自定义 TextBox 时,应用程序崩溃并出现以下异常:
IOException: Die Ressource "resources/mytextboxstyle.xaml" kann nicht gefunden werden.
(找不到资源)
但是,如果我不使用 MergedDictionary 方法并将所有样式 XAML 直接添加到 Generic/Themes.xaml 文件中,则一切正常。
我尝试将 MyTextBoxStyle.xaml 文件的 Build Action 更改为 Resource, Embedded Resource 但这没有帮助。如何使用 MergedDictionaries 并且仍然能够在其他程序集中使用样式化控件?