我正在尝试从可执行文件文件夹中的外部未编译的 XAML 文件加载样式,以便轻松设置主题。不幸的是,我无法这样做,因为 XAML 文件中使用的每个自定义命名空间都会引发异常。如果我使用 Application.LoadComponent 会加载相同的文件,但我希望它从外部加载。
这是我用来加载 xaml 文件的方法:
void LoadThemeExternal(string name)
{
var path = "Themes/" + name + ".xaml";
ResourceDictionary resourceDict;
using (FileStream fs = new FileStream(path, FileMode.Open))
resourceDict = (ResourceDictionary)XamlReader.Load(fs); // This line throws an exception.
Resources.MergedDictionaries.Add(resourceDict);
}
这是我创建的 XAML 文件,无法使用此方法加载:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Effects="clr-namespace:CleverDock.Effects" xmlns:Controls="clr-namespace:CleverDock.Controls">
<Style TargetType="Image" x:Key="IconImageStyle">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="RenderOptions.BitmapScalingMode" Value="HighQuality"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
<Setter Property="Margin" Value="0,0,0,10"/>
<Setter Property="Image.Effect">
<Setter.Value>
<Effects:BrightnessEffect Brightness="0"/>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
异常发生在 XamlReader.Load(fs)
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: 'Cannot create unknown type '{clr-namespace:CleverDock.Effects}BrightnessEffect'.' Line number '12' and line position '18'.
它尝试加载的效果是自定义 ShaderEffect,当 XAML 加载到已编译的资源中时,该效果可以正常工作。