1

I am designing a WPF appliation using .NET 7.0 (Visual Studio 2022). I have the following UserControl:

<UserControl x:Class="MyApp.Views.Test"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyApp.Views"
             xmlns:vm="clr-namespace:MyApp.Views.ViewModels"
             mc:Ignorable="d" 
             d:DataContext="{d:DesignInstance Type=vm:TestViewModel, IsDesignTimeCreatable=True}"
             d:DesignHeight="450" d:DesignWidth="800">
  <UserControl.DataContext>
    <vm:TestViewModel/>
  </UserControl.DataContext>
  <StackPanel>
    <Image Source="{Binding ImgSrc}" HorizontalAlignment="Center" MaxHeight="100"/>
    <TextBlock Text="{Binding Text}" HorizontalAlignment="Center" Foreground="Silver"/>
  </StackPanel>
</UserControl>

Here is myViewModel:

internal sealed class TestViewModel
{
  public Uri ImgSrc => new Uri("/Resources/MyImage.png", UriKind.Relative);
  public string Text => "This is the text";
}

Note that MyImage.png was indeed added to MyApp in the Resources folder and that its build-action was set to "Resource".

If I insert this UserControl in my MainWindow and run the app, the UserControl behaves as expected and the image and text are properly displayed.

The problem is actually in the designer. Whether in the designer of the UserControl itself or in the designer of the MainWindow, no matter what I tried, the image never shows up. Now I know that my designer DataContext is properly set and that my bindings as correct because the TextBlock's Text is properly displayed in the designer. Only the image is missing.

What am I doing wrong or missing here?

Gilles jr Bisson
  • 449
  • 4
  • 11
  • 1
    An assembly resource file (with Build Action Resource) should be loaded by a [Resource File Pack URI](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/pack-uris-in-wpf?redirectedfrom=MSDN&view=netframeworkdesktop-4.8#Resource_File_Pack_URIs___Local_Assembly): `new Uri("pack://application:,,,/Resources/MyImage.png")`, optionally including the referenced assembly: `new Uri("pack://application:,,,/YourAssembly;component/Resources/MyImage.png`)` – Clemens Mar 29 '23 at 06:14
  • 1
    Be aware that it is not necessary to have the image file copied to the output directory, just in case you set that option. – Clemens Mar 29 '23 at 06:17

0 Answers0