Search code examples
wpfmvvmbindingimagesource

Binding an ImageSource object directly to an Image source in XAML/WPF?


I have the following XAML code:

<ListBox ItemsSource="{Binding Languages}">  
    <ListBox.ItemTemplate>  
        <DataTemplate>  
            <StackPanel>  
                <Image Source="{Binding LanguageIcon}" />  
                <Label Content="{Binding LanguageName}" />  
            </StackPanel>  
        </DataTemplate>  
    </ListBox.ItemTemplate>  
</ListBox>  

and in the model class:

class Language {  
    public string LanguageName;  
    public ImageSource LanguageIcon;  
}  

my modelview class contains:

public List<Language> Languages;

which gets filled with:

Languages.Add(new Language("A",new BitmapImage(new Uri("Resources/a.ico",
    UriKind.Relative))));  
Languages.Add(new Language("B",new BitmapImage(new Uri("Resources/b.ico",
    UriKind.Relative))));  

When I run the project, all my language names are shown in the list, but not the icons... Why does this happen and how can I ensure that my icons are shown? (I am sure that the resources do exist as the BitmapImages don't throw errors)


Solution

  • Try changing your Uri path to...

    "../Resources/a.ico"
    

    EDIT:

    If you are trying to reference the images in a differing assembly try using the pack syntax...

    pack://application:,,,/ReferencedAssembly;component/Resources/a.ico
    

    ...where ReferencedAssembly is the assembly containing your images.