How do I bind an Image Source?

梦想与她 提交于 2019-12-05 17:33:50

In your case, it can be very easy!

Add the images as resources to your project, then in XAML use something like the following:

<Button HorizontalAlignment="Left" Margin="20,0,0,20" VerticalAlignment="Bottom" Width="50" Height="25">
    <Image Source="image.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
    </Image>
</Button>

Or, the more complicated way:

If you use the MVVM Pattern, you can do the following

In your XAML:

<Button Focusable="False" Command="{Binding CmdClick}" Margin="0">
    <Image Source="{Binding ButtonImage}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
    </Image>
</Button>

In your ViewModel:

private Image buttonImage;

public Image ButtonImage 
{
    get
    {
       return buttonImage;
    }
}

And somewhere in the constructor of your ViewModel or the initialisation of it:

BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri("image.png", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();

buttonImage = new Image();
buttonImage.Source = src;

In your XAML:

 <Button Focusable="False" Command="{Binding CmdClick}" Margin="0">
     <Image Source="{Binding ImageSource,UpdateSourceTrigger=PropertyChanged} HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
     </Image>
 </Button>

In your ViewModel:

 private BitmapImage _ImageSource;
 public BitmapImage ImageSource
 {
     get { return this._ImageSource; }
     set { this._ImageSource = value; this.OnPropertyChanged("ImageSource"); }
 }

 private void OnPropertyChanged(string v)
 {
     // throw new NotImplementedException();
     if (PropertyChanged != null)
         PropertyChanged(this, new PropertyChangedEventArgs(v));
 }
 public event PropertyChangedEventHandler PropertyChanged;

And somewhere in the constructor of your ViewModel or the initialisation of it:

 string str = System.Environment.CurrentDirectory;
 string imagePath = str + "\\Images\\something.png";
 this.ImageSource = new BitmapImage(new Uri(imagePath, UriKind.Absolute));

OR:

 string imagePath = "\\Images\\something.png";
 this.ImageSource = new BitmapImage(new Uri(imagePath, UriKind.Relative));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!