[英]Loading XAML files at runtime cannot find namespaces
我正在嘗試從可執行文件的文件夾中的外部未編譯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時,該效果很好。
發現我的錯誤! 我需要在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加載就沒有問題了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.