我正在尝试从可执行文件的文件夹中加载外部未编译的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加载到已编译的资源中时,它可以正常工作。
答案 0 :(得分:0)
发现我的错误!我需要在ResourceDictionary中指定; assembly = CleverDock ,如下所示:
<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;assembly=CleverDock">
然后Xaml加载没有问题