简体   繁体   中英

WPF/MVVM - Initialize image from XAML and bind to property in ViewModel

I have an application written in WPF MVVM. I want to initialize an embedded image from XAML (so that I can see it in the designer) but also bind it to the ViewModel so I can manipulate from code. I can successfully initialize it like this:

<Image x:Name="Image1" Source="pack://application:,,,/images/image1.png" Height="200" Width="55"  Opacity="0.35">

How do I bind it to the ViewModel?

If you want to see some data in design time you can define DesignTime viewmodel.

<Window
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=designTimeViewModels:DesignViewModel,
                                                       IsDesignTimeCreatable=True}"
/>

And to Bind Image Source use folowing code:

<Image Source="{Binding DisplayedImagePath}" />

ViewModel:

public string DisplayedImagePath 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

from this topic: Binding an Image in WPF MVVM

You could use FallbackValue...

    <BitmapImage x:Key="Image1" UriSource="pack://application:,,,/images/image1.png" />

    <Image x:Name="Image1" Source={Binding Image1, FallbackValue={StaticResource Image1}}" />

This has the possible downside of having your image how up at run time if the conditions for use of the fallback value is triggered; so you would need to avoid that situation.

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