首页 > 解决方案 > 如何在 ListView x:name 内的 Views 中访问 x:name?是否可以设置不同形式的用户输入?

问题描述

我对 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 名称在当前上下文中不存在。有没有人有任何智慧可以借给我如何克服这个障碍?

提前致谢!

标签: c#xamllistviewxamarinxamarin.forms

解决方案


看看MVVM,你会更清楚地理解设计。使用绑定 ViewMode 时,不建议我们直接处理 Control。另外,如果使用DataTemplate,我们也不会得到 Control by x:Name

不必担心如何获取x:Name控件,只需关注您要实现的功能即可。它会使用 MVVM 来实现你想要的功能。

例如,我的 Xaml 代码如下:

<ListView x:Name="MyListView"
            HasUnevenRows="True"
            RowHeight="150"
            CachingStrategy="RecycleElement"
            ItemSelected="MyListView_ItemSelected"
            ItemsSource="{Binding myItems}"
            IsVisible="True">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                    <StackLayout Orientation="Horizontal"
                                        VerticalOptions="Center">
                            <Label Text="Hello World"
                                    HorizontalOptions="StartAndExpand"></Label>
                            <Label Text="{Binding Address}"
                                    HorizontalOptions="CenterAndExpand"></Label>
                            <Label Text="{Binding eMail}"
                                    HorizontalOptions="CenterAndExpand"></Label>
                            
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

然后我将编写如下代码以使其显示我的需求:

public PageListView()
{
    InitializeComponent();

    var myItems = new List<Contacts>();
    myItems.Add(new Contacts() {Address="1",eMail="1" });
    myItems.Add(new Contacts() { Address = "2", eMail = "2" });
    myItems.Add(new Contacts() { Address = "3", eMail = "3" });
    myItems.Add(new Contacts() { Address = "4", eMail = "4" });
    myItems.Add(new Contacts() { Address = "5", eMail = "5" });

    this.BindingContext = this;
   
}

Contacts.cs</p>

public class Contacts
{
    public string Address { get; set; }
    public string eMail { get; set; }
}

效果:

在此处输入图像描述

=====================================更新============== =================

如果需要默认值,则定义一个备用值

<Label Text="{Binding Address, FallbackValue='Address unknown'}"
       ... />

ItemSource从一个休息 api 设置,这里是示例

protected async override void OnAppearing ()
{
    base.OnAppearing ();

    listView.ItemsSource = await App.TodoManager.GetTasksAsync ();
}

推荐阅读