C# 仅当文件存在时加载资源字典

C# 仅当文件存在时加载资源字典,c#,wpf,C#,Wpf,有没有办法仅在资源文件存在时加载资源字典? 在下面的例子中,我只希望在文件'Resources/AdditionalStyles.xaml'存在时才允许使用资源字典 <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Styles.xaml" />

有没有办法仅在资源文件存在时加载资源字典? 在下面的例子中,我只希望在文件'Resources/AdditionalStyles.xaml'存在时才允许使用资源字典

<ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles.xaml" />
                <ResourceDictionary Source="Resources/AdditionalStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>

您可以尝试通过代码动态加载它,而不是像某人在中尝试的那样在App.xaml中插入引用:

如果我没有弄错,它应该给出一个异常,如果所述资源不存在,您可以捕获该错误,或者检查文件是否存在于路径XYZ中,并执行您希望继续执行的其他逻辑:

var foo = new Uri("pack://siteoforigin:,,,/resources/leaf_styles.xaml", UriKind.RelativeOrAbsolute);
Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = foo });
动态加载它:

   private void LoadDynamicResource(String sStyle)
    {
        FileInfo fi1 = new FileInfo(sStyle);
        if(fi1.Exists)
        {
            using (FileStream fs = new FileStream(sStyle, FileMode.Open))
            {
               ResourceDictionary dic = (ResourceDictionary)XamlReader.Load(fs);
               Resources.MergedDictionaries.Clear();
               Resources.MergedDictionaries.Add(dic);
            }
        }
    }
您可以覆盖App.xaml.cs中的OnStartup方法,然后检查是否存在该文件,如果确实存在,则加载该文件:

protected override void OnStartup(StartupEventArgs e)
{
    var fileName = Environment.CurrentDirectory() + @"\Resources\AdditionalStyles.xaml";

    // Check if the AdditionalStyles.xaml file exists
    if (File.Exists(fileName)
    {
        try
        {
            // try and load the file as a dictionary and add it the dictionaries
            var additionalStylesDict = (ResourceDictionary)XamlReader.Load(fs);
            Resources.MergedDictionaries.Add(additionalStylesDict);
        }
        catch (Exception ex)
        {
            // something went wrong loading the resource file
        }
    }

    // any other stuff on startup

    // call the base method
    base.OnStartup(e);
}

如果源代码中存在ResourceDictionary,则可以动态加载它。您可以调整本教程以检查文件是否存在,如果存在,则加载该文件: