2012-09-11 13 views
7

He incluido un archivo de icono dentro de Resources.resx que me gustaría mostrar en un TreeViewItem que está dentro de un stackpanel.Cómo usar Resources.resx para vincular imágenes

1) ¿Se pueden usar archivos .ico para este propósito? ¿O tiene que ser .bmp o jpg?

2) ¿Qué configura la fuente como en XAML? El siguiente código no funcionó para mí

<StackPanel Orientation="Horizontal"> 
    <Image Margin="2" Source="/Resources/Folder_Back.ico" /> 
    <TextBlock Margin="2" Text="{Binding ProgramName}" 
    Foreground="White" FontWeight="Bold"/> 
</StackPanel> 

Respuesta

5

no se puede hacer eso. que funcionó sólo en winforms

ver este post para más información

Different way how add image to resources

utilizar el método que se muestra en este post

WPF image resources

lugar

cita:

Si va a utilizar la imagen en varios lugares, entonces vale la pena cargar los datos de imagen solo una vez en la memoria y luego compartirla entre todos los elementos Image.

Para ello, cree un BitmapSource como un recurso en alguna parte:

<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" /> 

Luego, en el código, usar algo como:

<Image Source="{StaticResource MyImageSource}" /> 

En mi caso, me di cuenta que tenía que establezca el archivo Image.png para tener una acción de compilación de Resource en lugar de solo Content. Esto hace que la imagen sea transportada dentro de su ensamblado compilado.

+0

¿Puedo usar archivos .ico para fuente de imagen? – l46kok

+0

sí. solo use .ico en lugar de png. incluso puede editarlo dentro de VS – Nahum

12

Aquí es un truco para acceder a la imagen en el archivo de recursos:

Accessing image from Resource File in XAML markup

primer lugar es necesario añadir una referencia a las propiedades del proyecto así:

xmlns:properties="clr-namespace:MyProject.Properties" 

Y luego acceder a ella a través de XAML como esto:

<image source="{Binding Source={x:Static properties:Resources.ImageName}}" /> 

Puede usar PNG/JPG/BMP así como el archivo ICO, pero todos recomiendan PNG.

+6

Esto no funciona. Nada aparece. Intenté usarlo como un icono y como una imagen. –

3

para hacer que la solución del trabajo de Qorbani añada un convertidor a la fuente de la imagen. ¡Encuadernación!

XAML - Espacios de nombres

xmlns:properties="clr-namespace:YourNameSpace.Properties" 
xmlns:converter="clr-namespace:YourNameSpace.Converter" 

Xaml - Recursos (control de usuario o ventana)

<UserControl.Resources> 
     <ResourceDictionary> 
       <converter:BitmapToImageSourceConverter x:Key="BitmapToImageSourceConverter" /> 
     </ResourceDictionary> 
</UserControl.Resources> 

Código Xaml

<StackPanel Orientation="Horizontal"> 
        <Image Width="32" Height="32" Source="{Binding Source={x:Static properties:Resources.Import}, Converter={StaticResource BitmapToImageSourceConverter}}" Stretch="Fill" /> 
        <TextBlock Margin="5" HorizontalAlignment="Center" VerticalAlignment="Center">Import</TextBlock> 
</StackPanel> 

BitmapToImageSourceConverter.cs

using System; 
using System.Collections.Generic; 
using System.Drawing; 
using System.Drawing.Imaging; 
using System.Globalization; 
using System.Linq; 
using System.Text; 
using System.Windows.Data; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 

namespace YourNameSpace 
{ 
    public class BitmapToImageSourceConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      var bitmap = value as System.Drawing.Bitmap; 
      if (bitmap == null) 
       throw new ArgumentNullException("bitmap"); 

      var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); 

      var bitmapData = bitmap.LockBits(
       rect, 
       ImageLockMode.ReadWrite, 
       System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

      try 
      { 
       var size = (rect.Width * rect.Height) * 4; 

       return BitmapSource.Create(
        bitmap.Width, 
        bitmap.Height, 
        bitmap.HorizontalResolution, 
        bitmap.VerticalResolution, 
        PixelFormats.Bgra32, 
        null, 
        bitmapData.Scan0, 
        size, 
        bitmapData.Stride); 
      } 
      finally 
      { 
       bitmap.UnlockBits(bitmapData); 
      } 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 
+0

¿Por qué no hay más votos hacia arriba? Esta solución hace el trabajo. – AndyUK

Cuestiones relacionadas