Search code examples
c#.netwpfmaui

How to share images across different .NET project types? (WPF, MAUI)


We are working on a new project and we're trying to put all of our images into one assembly.

Core.Images.csproj
- PNG
-- Image1.png
-- Image2.png
- SVG
-- Image1.svg
-- Image2.svg

Our main application will be a WPF application. We intend to use DevExpress and want to use their SplashScreenManager which requires a DXSplashScreenViewModel. The only option to put a logo into this ViewModel is an Uri object. As far as I know this pretty common for WPF applications. The intended URI format is something like this: pack://application:,,,/Core.Images;component/PNG/Image2.png But this only works as long as the PropertyGroup inside of Core.Images.csproj has the build target set to net6.0-windows and UseWpf enabled. Also the files must be set as "Resource".

  <PropertyGroup>
    <TargetFramework>net6.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
    ...
  </PropertyGroup>
  ...
  <ItemGroup>
    <Resource Include="PNG\Image1.png" />
    <Resource Include="PNG\Image2.png" />
    <Resource Include="SVG\Image1.svg" />
    <Resource Include="SVG\Image2.svg" />
  </ItemGroup>
  ...

The issue we come across now is that we need to add another app to the solution that is developed in .NET MAUI. We have been trying to make this little assembly compatible to both projects, but can't seem to find a way.

Is it even possible to achieve that with one library or will we need to copy used images to a second assembly?


Solution

  • Assuming you are targeting Android in your MAUI app, your Core.Images.csproj should look something like this:

    <PropertyGroup>
      <TargetFrameworks>net6.0-windows;net6.0-android</TargetFrameworks>
      <ImplicitUsings>enable</ImplicitUsings>
      <Nullable>enable</Nullable>
    </PropertyGroup>
    
    <PropertyGroup Condition="'$(TargetFramework)' == 'net6.0-windows'">
        <UseWPF>true</UseWPF>
    </PropertyGroup>
    
    <PropertyGroup Condition="'$(TargetFramework)' == 'net6.0-android'">
        <UseMaui>true</UseMaui>
    </PropertyGroup>
    
    <ItemGroup Condition="'$(TargetFramework)' == 'net6.0-windows'">
        <Resource Include="Images\image.png" />
    </ItemGroup>
    
    <ItemGroup Condition="'$(TargetFramework)' == 'net6.0-android'">
        <MauiImage Include="Images\*" />
    </ItemGroup>
    

    You should deal with other platforms too. I hope this is helpful, works on my side. Feel free to ask If somethink is not understabdable. Note, that your images names can only contain lowercase lettering, digits and '_'.