user6501892
user6501892

Reputation:

C# WPF loading images from Resources

For some reason, I am getting the assembly name for every time I am trying to bind to an Image. I am getting System.Windows.Control.Image in my TextBlock rather than the image itself.

My XAML looks like this

<TextBlock FontSize="16">
     <TextBlock.Text>
        <MultiBinding StringFormat=" {0} {1}">
           <Binding Path="Icon"></Binding>
           <Binding Path="Name"></Binding>
          </MultiBinding>
      </TextBlock.Text>
</TextBlock> 

And in my Model class, I am creating an Image like this:

public Image Icon
{
   get
   {
       if (isFolder)
       {
           Image folderImage = new Image();
           BitmapImage logo = new BitmapImage();
           logo.BeginInit();
           logo.UriSource = new Uri("pack://application:,,,/ComputerProject;component/Resources/FolderIcon.jpg");
           logo.EndInit();
           folderImage.Source = logo;
           return folderImage;
       }
       else
       {
            return new Image(); //TODO
       }
   }
}

Can this be done in a TextBlock? I have tried using multiple textblocks rather than doing the StringFormatting but that didn't work either.

Upvotes: 1

Views: 93

Answers (1)

Clemens
Clemens

Reputation: 128013

Simply use an Image and a TextBlock element:

<StackPanel Orientation="Horizontal">
    <Image Source="{Binding Icon}"/>
    <TextBlock Text="{Binding Name}"/>
</StackPanel>

where the Icon property is of type ImageSource, Uri or just string.

Example:

public ImageSource Icon
{
    get
    {
        if (isFolder)
        {
            return new BitmapImage(new Uri(
                "pack://application:,,,/ComputerProject;component/Resources/FolderIcon.jpg"));
        }

        return null; //TODO
    }
}

Upvotes: 2

Related Questions