【问题标题】:Loading XAML files at runtime cannot find namespaces在运行时加载 XAML 文件找不到命名空间
【发布时间】:2019-08-30 18:48:47
【问题描述】:

我正在尝试从可执行文件文件夹中的外部未编译 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 在已编译资源中加载时可以正常工作。

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    发现我的错误!我需要像这样在 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 加载没有问题

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多