如何使用带有Xamarin的MVVM在XAML中动态更改图像源

时间:2016-08-19 01:51:32

标签: c# image xaml xamarin xamarin.forms

我正在尝试更改ContentPage上的图片来源属性。我正在使用绑定上下文来执行此操作。但是,即使我在模型视图中更改了源代码,也不会在我的视图中更新图像。

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>

3 个答案:

答案 0 :(得分:2)

Image组件接受ImageSourceFileImageSourceStreamImageSource等)。幸运的是,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;
    }
}

答案 1 :(得分:1)

当您绑定ImageSource时,请使用Xamarin.Forms.ImageSource作为您的媒体资源的返回类型。或者,如果要指定文件路径,则可以使用它的派生类,如FileImageSource。还要确保路径存在于本机项目中。

答案 2 :(得分:0)

首先在视图模型中添加de ImageSource,不要忘记包含Xamarin.Forms依赖项...

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

之后,在你的xaml文件中包含de source binding:

     <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); }
    }