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