Reputation: 61
I'm trying to change an image source property on a ContentPage
. I´m using a binding context to do this. But, even if I change the source in my model view, this don't update the image in my view.
UpdateMethod()
{
imageSource1 = imageSource[1];
}
public string ImageSource1
{
get
{
return imageSource1;
}
set
{
imageSource1 = value;
this.Notify("ImageSource1");
}
}
The XAML:
<ContentView HorizontalOptions="Center" Grid.Row="0" >
<Image ClassId = "1" Source="{Binding ImageSource1}" BindingContextChanged="Handle_BindingContextChanged">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding OnTapGestureRecognizerTappedCommand1}" NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image>
</ContentView>
Upvotes: 5
Views: 12449
Reputation: 953
First add de ImageSource in your view model, don´t forget to include Xamarin.Forms dependencys...
private ImageSource _imageSource;
public ImageSource ImageSource
{
get { return _imageSource; }
set
{
_imageSource= value;
PropertyChanged(this, new PropertyChangedEventArgs("ImageSource"));
}
}
after this, include de source binding in you xaml file:
<Image Source="{Binding ImageSource}">
<!--<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ImageTapCommand}" />
</Image.GestureRecognizers>-->
</Image>
Here is a "prism example"
private ImageSource _imageSource;
public ImageSource ImageSource
{
get { return _imageSource; }
set { SetProperty(ref _imageSource, value); }
}
Upvotes: 1
Reputation: 3698
Image
component accepts ImageSource
(FileImageSource
, StreamImageSource
etc). Luckily ImageSource class have implicit operator against string which creates itself from string regarding format(url or path). Check below Example:
Xaml
<Image Source="{Binding ImagePath}">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ImageTapCommand}" />
</Image.GestureRecognizers>
</Image>
ViewModel.cs:
public class SomeViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ICommand ImageTapCommand { get; set; }
private string imagePath;
public string ImagePath
{
get { return imagePath; }
set
{
imagePath = value;
PropertyChanged(this, new PropertyChangedEventArgs("ImagePath"));
}
}
public SomeViewModel()
{
ImageTapCommand = new Command(CmdTapImage);
}
private void CmdTapImage()
{
ImagePath = YourNewImagePath;
}
}
Upvotes: 4
Reputation: 11787
When you are Binding the ImageSource
use the Xamarin.Forms.ImageSource
as the return type of your property. Or you can use it's derived classes like FileImageSource
if you are specifying a filepath. Also make sure that the path is present in the native projects.
Upvotes: 1