2016-10-04 61 views
2

只有在资源文件存在的情况下才有加载资源字典的方法吗? 在下面的情况下,我只希望让资源字典当文件“资源/ AdditionalStyles.xaml”存在仅当文件存在时才加载资源字典

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

这是可能的如果它存在于代码中,则动态加载'ResourceDictionary'。您可以修改本教程以检查文件是否存在,然后加载它:https://weblogs.asp.net/psheriff/load-resource-dictionaries-at-runtime-in-wpf –

回答

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

感谢您的回复! – user1034912

1

您可以通过动态加载它通过代码,而不是在App.xaml中插入类似的参考尝试有人试图做:Dynamically loading resource dictionary files to a wpf application gives an error

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

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

感谢您的回复! – user1034912

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

感谢您的回复! – user1034912