Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用带Xamarin的MVVM在XAML中动态更改图像源_C#_Image_Xaml_Xamarin_Xamarin.forms - Fatal编程技术网

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

C# 如何使用带Xamarin的MVVM在XAML中动态更改图像源,c#,image,xaml,xamarin,xamarin.forms,C#,Image,Xaml,Xamarin,Xamarin.forms,我正在尝试更改ContentPage上的图像源属性。我使用绑定上下文来实现这一点。但是,即使我在模型视图中更改了源,这也不会更新视图中的图像 UpdateMethod() { imageSource1 = imageSource[1]; } public string ImageSource1 { get { return imageSource1; } set { imageSource1 = value;

我正在尝试更改
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>


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

Image
组件接受
ImageSource
FileImageSource
StreamImageSource
等)。幸运的是,ImageSource类具有针对字符串的隐式运算符,该字符串根据有关格式(url或路径)的字符串创建自身。检查以下示例:

Xaml

<Image Source="{Binding ImagePath}">
  <Image.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding ImageTapCommand}" />
  </Image.GestureRecognizers>
</Image>

首先在视图模型中添加de ImageSource,别忘了包括Xamarin.Forms Dependency

    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>

当图像在listview中时如何更改?
     <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); }
    }