How can I set this Image Source in XAML?
Currently, I have this in MainWindow.xaml:
<Image Name="LogoImage" />
And this in MainWindow.xaml.cs:
public ImageSource LogoImageSource { get; set; }
开发者_运维百科
....
var rm = new ResourceManager("Project.Properties.Resources", GetType().Assembly);
var logoBmp = (Bitmap) rm.GetObject("CompanyLogo");
if (logoBmp != null)
{
var hBitmap = logoBmp.GetHbitmap();
ImageSource src =
Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
LogoImageSource = src;
}
var logoBinding = new Binding("LogoImageSource");
logoBinding.Source = this;
LogoImage.SetBinding(System.Windows.Controls.Image.SourceProperty, logoBinding);
I do it this way because I like to keep images as embedded resources, so there's not a bunch of random files floating around in the users install dir.
But how can I manage the image binding (the last 3 lines of code) from XAML and not C#?
Or, if anyone has any input on how they manage image resources, please share it with me.
In WPF, you need to use the compile action of Resource
, not Embedded Resource
. Then you can access it like you want to.
EDIT
If you have to use Embedded Resources, you could do it with an IValueConverter
. You're basically moving the code into a reusable class, but it would look something like this:
public class ImageLoadingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || !(value is string)) return null;
var rm = new ResourceManager("Project.Properties.Resources", GetType().Assembly);
using (var stream = rm.GetStream((string)value))
{
return BitmapFrame.Create(stream);
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
You'd then use it like so:
<lcl:ImageLoadingConverter x:Key="imageLoader" />
...
<Image Source="{Binding Source=LogoImage.png, Converter={StaticResource imageLoader}}" />
精彩评论