简体   繁体   中英

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.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM