簡體   English   中英

C# - 從不同程序集中的文件資源加載圖像

[英]C# - Loading image from file resource in different assembly

C# - 從不同程序集中的文件資源加載圖像

我有一個PNG圖像文件存儲在一個名為SomeProject的項目中,並在同一個項目中使用XAML進行了多次顯示。 不同的程序集中,我現在希望訪問相同的圖像。 以前我只是指定一個工作正常的實際文件的相對路徑。 但是,當我構建發布安裝程序時,圖像文件將打包到SomeProject.DLL中。

有沒有簡單的方法我可以從另一個程序集訪問PNG文件,而不是簡單地將文件本地復制到第二個項目? 我雖然可能使用'pack://'但我沒有太多運氣。

// SomeOtherProject.SomeClass.cs ...

Image logo = new Image();
BitmapImage logoSource = new BitmapImage();
eChamSource.BeginInit();

// Following line works fine is Visual Studio, but obviously not after installation
// logoSource.UriSource = new Uri(@"..\SomeProject\Resources\Images\logo.png", UriKind.Relative);

logoSource.UriSource = new Uri("pack://application:,,,/SomeProject;component/Resources/Images/logo.png");
logoSource.EndInit();

logo.Width = 100; logo.Height = 100;
logo.Source = logoSource;

任何建議都會很好。

如果要用作Content的圖像位於another assembly集中,則必須copy它們copymain projects directory

您可以使用Build事件來執行此操作:

右鍵單擊包含images -> Properties -> Buil Events ->項目images -> Properties -> Buil Events ->構建images -> Properties -> Buil Events ->編輯構建images -> Properties -> Buil Events ->圖像復制到main project directory

然后你必須使用它

pack://application:,,,/ContentFile.xaml

(要么)

如果你需要在子文件夾中

pack://application:,,,/Subfolder/ContentFile.xaml

有關更多信息,請查看此信息http://msdn.microsoft.com/en-us/library/aa970069.aspx

嘗試按如下方式加載其他程序集:

Application.LoadComponent(new Uri(@"AnotherAssembly;;;component\AnotherResourceFilePath/logo.png", UriKind.Relative)));

LoadComponent函數返回一個對象。 您可以將其強制轉換為適當的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM