2016-08-19 65 views
2

我试图更改ContentPage上的图像源属性。我正在使用绑定上下文来执行此操作。但是,即使我在模型视图中更改了源代码,这也不会更新我的视图中的图像。如何在XAML中使用MVVM动态地在XAML中更改图像源Xamarin

UpdateMethod() 
{ 
    imageSource1 = imageSource[1]; 
} 

public string ImageSource1 
{ 
    get 
    { 
     return imageSource1; 
    } 

    set 
    { 
     imageSource1 = value; 
     this.Notify("ImageSource1"); 
    } 
} 

的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> 

回答

1

当你绑定ImageSource使用Xamarin.Forms.ImageSource为你的财产的返回类型。或者,如果要指定文件路径,则可以使用它的派生类,如FileImageSource。还要确保路径出现在本地项目中。

+1

它为我工作。 –

1

Image组件接受ImageSourceFileImageSource,StreamImageSource等)。幸运的是,ImageSource类具有隐式操作符,用于根据格式(url或path)从字符串创建自己的字符串。检查下例:

的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; 
    } 
} 
0

首先在您的视图模型添加DE ImageSource的,不要忘了包括Xamarin.Forms dependencys ...

private ImageSource _imageSource; 
public ImageSource ImageSource 
{ 
    get { return _imageSource; } 
    set 
    { 
     _imageSource= value; 
     PropertyChanged(this, new PropertyChangedEventArgs("ImageSource")); 
    } 
} 

在此之后,包括德源在你XAML文件绑定:

 <Image Source="{Binding ImageSource}"> 
     <!--<Image.GestureRecognizers> 
      <TapGestureRecognizer Command="{Binding ImageTapCommand}" /> 
     </Image.GestureRecognizers>--> 
    </Image> 

这里是一个“棱镜例如”

 private ImageSource _imageSource; 
    public ImageSource ImageSource 
    { 
     get { return _imageSource; } 
     set { SetProperty(ref _imageSource, value); } 
    }