2016-08-19 80 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); } 
    }