在ClassLibrary DLL中加载XAML资源文件

时间:2014-04-24 12:57:46

标签: c# wpf dll

我有一个WPF应用程序,其中包含标记为ressource(buildprocess)的xaml文件。在运行时,我可以使用以下代码加载和访问该文件:

Uri uri = new Uri("some.xaml", UriKind.Relative);
System.Windows.Resources.StreamResourceInfo sri = Application.GetResourceStream(uri);
System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
Border savedBorder = reader.LoadAsync(sri.Stream) as Border;

将功能和xaml文件移动到类库中并将“some.xaml”标记为资源,上面的代码失败,IOException“资源”some.xaml“无法找到”。这在逻辑上听起来是因为我无法在类库中成功访问Application.GetResourceStream

System.Reflection.Assembly
   .GetExecutingAssembly()
   .GetManifestResourceStream("some.xaml") ;

返回null

在dll中访问此类文件的正确方法是什么?

3 个答案:

答案 0 :(得分:0)

您的资源名称不正确。 Visual Studio使用完全限定名称(例如命名空间和资源名称)创建资源。

请参阅How to read embedded resource text file

尝试类似:

 System.Reflection.Assembly
   .GetExecutingAssembly()
   .GetManifestResourceStream("mycompany.myproduct.some.xaml");

答案 1 :(得分:0)

我使用完整的资源名称。 这段代码解决了问题:

Assembly assembly = GetExecutingAssembly(); 
using (var stream = assembly.GetManifestResourceStream(this.GetType(), "some.xaml")) 
{ 
   StreamReader sr = new StreamReader(stream); 
   string Content = sr.ReadToEnd(); 
} 

因此无需指定完整资源名称。

答案 2 :(得分:0)

两个答案都是正确的,但我必须注意到一个不精确的地方:资源名称应采用其他格式。

var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("UCM.WFDesigner.Resources.Flows.DefaultFlow.xaml");

UCM.WFDesigner是我的集会名称, Resources.Flows是文件夹名称, DefaultFlow.xaml是xaml名称。