![](/img/trans.png)
[英]Xamarin.Forms find container listview from within a data template
[英]Accessing an Image from Data Template in Xamarin.Forms
我构建了一个页面,我需要从数据模板访问图像。 图像名称为 image_3。
我的 xaml 是这样构造的(只是数据模板的一个想法):
<ContentPage.Resources> <ResourceDictionary x:Name="ResourceDictionary"> <DataTemplate x:Key="CustomKey"> <Grid> <StackLayout> <Image x:Name="ImageToBeChanged"/> <Button Clicked="BtnClicked"/> </StackLayout> </Grid> </DataTemplate> </ResourceDictionary> </ContentPage.Resources>
现在,一切正常并显示正确,但在方法中
BtnClicked() 我想动态设置 ImageToBeChanged 的 Source,我无法访问 C# 层中的 ImageToBeChanged。
谢谢你的所有想法!
就像 Jason 所说,您可以使用数据绑定。
Xaml:
<ContentPage.Resources>
<ResourceDictionary x:Name="ResourceDictionary">
<DataTemplate x:Key="CustomKey">
<ViewCell>
<Grid>
<StackLayout>
<Image x:Name="ImageToBeChanged" Source="{Binding image}" />
<Button Clicked="BtnClicked" />
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<!-- Place new controls here -->
<ListView
x:Name="listView"
ItemTemplate="{StaticResource CustomKey}"
ItemsSource="{Binding images}" />
</StackLayout>
</ContentPage.Content>
后面的代码:
public partial class MainPage : ContentPage
{
public List<Info> images { get; set; }
public MainPage()
{
InitializeComponent();
images = new List<Info>()
{
new Info(){ image="pink.jpg" },new Info(){ image="pink.jpg" },new Info(){ image="pink.jpg" },new Info(){ image="pink.jpg" }
};
this.BindingContext = this;
}
private void BtnClicked(object sender, EventArgs e)
{
}
}
public class Info
{
public string image { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.