【发布时间】:2021-02-16 16:31:37
【问题描述】:
我对 Xamarin 还很陌生,正在制作一个应用程序,其中包含我希望可以选择喜欢/设置为最喜欢的功能的项目列表。
但是由于 ListView 中的 x 名称,我在访问图像视图和按钮视图 x 名称时遇到了问题。我尝试的是通过将 ListView、Button 和 Image 分成不同的网格行来获得与 ListView 中的项目一样多的图像和按钮。 遗憾的是,这导致 Listview 正常填充,但只显示一个图像和一个按钮。
这是我尝试过的: 我的 Xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:MyApp.Converters"
x:Class="MyApp.MainPage">
<StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
<Grid>
<ListView
x:Name="CategoryList"
SelectionMode="None"
ItemsSource="{Binding FavCategories}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Grid.Column="0" Text="{Binding ., Converter{converters:ToUpperConverter}}"></Label>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Image x:Name="ImgFav"
Grid.Column="2"
Source="{Binding IsFav}"></Image>
<Button x:Name="BtnFav"
Grid.Column="3"
Text="{Binding FavState}"
Clicked="BtnFav_Clicked"></Button>
</Grid>
</StackLayout>
</ContentPage>
我的 C#:
public async Task Load()
{
ApiService apiService = new ApiService();
Categories.Clear();
List<FavCategoryModel> favCategories = new List<FavCategoryModel>();
var categories = await apiService.GetCategories();
foreach (var category in categories)
{
Categories.Add(category);
}
foreach(var item in Categories)
{
favCategories.Add(new FavCategoryModel { Category = item, IsFavourite = false });
}
CategoryList.ItemsSource = favCategories.Select(c =>c.Category.ToString()).ToList();
var isFavourite = favCategories.Select(f => f.IsFavourite);
foreach(var isfav in favCategories)
{
if (favCategories.Any(f => f.IsFavourite) == false)
{
foreach(var category in categories)
{
ImgFav.Source = "nonFav.Png";
BtnFav.Text = "Like";
}
}
}
所以我知道如果我做对了,我应该能够操作 Button 和 Image,如果它们在 ListView 内,并获得与填充列表的类别相对应的行。 像这样:
<ListView
x:Name="CategoryList"
SelectionMode="None"
ItemsSource="{Binding FavCategories}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Grid.Column="0" Text="{Binding ., Converter{converters:ToUpperConverter}}"></Label>
<Image x:Name="ImgFav"
Grid.Column="2"
Source="{Binding IsFav}"></Image>
<Button x:Name="BtnFav"
Grid.Column="3"
Text="{Binding FavState}"
Clicked="BtnFav_Clicked"></Button>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
但导致我的 x 按钮和图像名称在当前上下文中不存在。 有没有人有什么智慧可以帮助我克服这个障碍?
提前致谢!
【问题讨论】:
-
您不能按名称访问模板中的项目。模板中的项目是在运行时动态生成的 - 您应该使用数据绑定来填充它们。
-
第二,您不能将模板中的项目分配给网格行/列,因为 ListView 包含在 Grid 中,模板中的项目将包含在 ListView 中。您可以在 ViewCell 中放置一个 Grid,然后将模板项放置在该 Grid 中。
-
@Jason Yea 抱歉忘记调整那部分,这就是我的意思是我尝试将网格放在 ViewCell 中。我将再次尝试数据绑定,遗憾的是我还没有完全掌握它的正确使用方法,但我唯一的线索是,这是正确的方法。
-
您将 ListView 绑定到
List<string>。而是将其绑定到List<FavCategoryModel>,然后将模板中的项目绑定到该模型上的不同属性。 -
检查 Bindings and Collections 或从模板项目开始并检查绑定以获取列表和详细信息。
标签: c# xaml listview xamarin xamarin.forms