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

时间:2016-10-04 10:20:12

标签: c# wpf

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

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

3 个答案:

答案 0 :(得分:1)

您可以尝试通过代码动态加载它而不是像App.xaml中那样插入引用:Dynamically loading resource dictionary files to a wpf application gives an error

如果我没有弄错,如果所述资源不存在则应该给出异常,你可以捕获该错误,或​​者检查文件是否存在于Path XYZ中并执行你想要继续的其他逻辑:

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

答案 1 :(得分:1)

动态加载:

   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);
            }
        }
    }

答案 2 :(得分:1)

您可以覆盖OnStartup中的App.xaml.cs方法,然后检查是否存在该文件,如果存在则加载该文件:

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);
}