在xamarin表单上动态绑定图像源 [英] Binding image source dynamically on xamarin forms
问题描述
我的问题是,我可以将字符串图像绑定到图像源吗?我有多个图像,如果条件,图像将会改变。所以:
Xamal表格上的Xaml:
< Image Source ={绑定someImage}Aspect =填充Grid.Row =2>< / Image>
Codebehind c#
public String someImage;
public String SomeImage
{
set
{
if(someImage!= value)
{
someImage = value;
}
}
获得
{
返回someImage;
}
}
InitializeComponent部分:
if(true)
{
someImage =backgroundListViewGren.png;
}
其他
{
someImage =backgroundListViewRed.png;
}
图片位于便携式项目的Images文件夹中
但是,这不起作用,也许我不会做什么,但我不明白。
任何解决方案?
我尝试使用ImageSource而不是字符串,但也不用。
我会在这里发布这个答案,因为它是我正在寻找的那个,我怀疑大多数人都是(并且谷歌目前在这里指导你,目前不是很有帮助如果使用XAML绑定图像:
XAML:
< Image>
< Image.Source>
< FileImageSource File = {Binding SomeImage} />
< /Image.Source>
< / Image>
然后在ViewModel中,C#:
public string SomeImage
{
get {return string.Format(prefix- {0} -suffix.png,OtherProperty); }
}
您可以使用更新,更好,但基本等效的c#而不是上述:
public string SomeImage => $ prefix- {} OtherProperty -suffix.png;
这当然是设置它的最简单方法,IMO :)。
编辑:不言而喻,但图片显然应位于每个平台项目的 Resources
文件夹中。
my question is, could I Binding string image to image source ? I have multiple image and the image will change on if condition. So:
Xaml on Xamarin forms:
<Image Source="{Binding someImage}" Aspect="Fill" Grid.Row="2"></Image>
Codebehind c#
public String someImage;
public String SomeImage
{
set
{
if (someImage != value)
{
someImage = value;
}
}
get
{
return someImage;
}
}
InitializeComponent part:
if(true)
{
someImage = "backgroundListViewGren.png";
}
else
{
someImage = "backgroundListViewRed.png";
}
the image is in "Images" folder on portable project
but this, doesn't work, maybe i wront something but I don't understand. Any solutions ?
I've tried with ImageSource and not string, but don't work too.
I'll post this answer here because it's the one I was looking for and I suspect most others are (and Google currently directs you here, which currently isn't super helpful).
How to bind an image using XAML:
XAML:
<Image>
<Image.Source>
<FileImageSource File={Binding SomeImage} />
</Image.Source>
</Image>
Then in the ViewModel, C#:
public string SomeImage
{
get { return string.Format("prefix-{0}-suffix.png", OtherProperty); }
}
Newer, better, but essentially equivalent c# you can use instead of the above:
public string SomeImage => $"prefix-{OtherProperty}-suffix.png";
This is certainly the easiest way to set it up, IMO :).
EDIT: It should go without saying, but the image should obviously be in the Resources
folder of the project for each platform.
这篇关于在xamarin表单上动态绑定图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!