【问题标题】:How to add and retrieve lists from a view in Xamarin forms?如何在 Xamarin 表单的视图中添加和检索列表?
【发布时间】:2019-02-03 23:18:03
【问题描述】:

我正在使用 .net 标准 2.0 为 android 制作一个 Xamarin 应用程序,并且我有相当大的对象要处理。我想为它们创建一些视图,将它们添加到列表中,然后用户可以从中选择,然后我检索所选对象并打开更详细的视图。

什么方法最适合这个?到目前为止,我将它们放在一个列表视图中,将几个属性拼接在一个字符串中,然后拆分选定的字符串并搜索匹配的对象,但这似乎很容易损坏,因为我不知道对象将具有什么价值,直到运行时。

我想将它们添加到网格中,因为这似乎是自定义布局的最佳选择,是否可以将这些值添加到网格并将 TapGestureRecognizer 附加到行,并以某种方式存储和接收选定的该行的对象?

【问题讨论】:

  • 您可以使用 DataTemplateSelector 根据您的数据标准返回不同的 DataTemplate,因此您的列表视图可以在单个列表视图中包含多达 20 个不同的数据视图(20 个 DataTemplate 是 Android 限制...)。 docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/… 你能否以编程方式根据数据创建网格,但我个人会通过 DataTemplateSelector 使用列表视图...

标签: c# object xamarin xamarin.forms


【解决方案1】:

如果您使用 ICommand,您可以简单地实现 TapGestureRecognizer。 首先在 XAML 文件中创建 GridView,如下所示:

<Grid>
  <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"/>
      <ColumnDefinition Width="*"/>
  </Grid.ColumnDefinitions>
  <Label Text = "{Binding @something}" GridRow = 0 GridColumn = 0/>
  <Grid.GestureRecognizers>
      <TapGestureRecognizer Command="{Binding TapCommand}"/>
  </Grid.GestureRecognizers>
</Grid>

之后在 c# 代码中设置绑定如下:

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.SetBinding (TapGestureRecognizer.CommandProperty, "TapCommand");
grid.GestureRecognizers.Add(tapGestureRecognizer);

那么你应该执行命令:

public class TapViewModel : INotifyPropertyChanged
{
  ICommand tapCommand;

  public TapViewModel () 
  {
    tapCommand = new Command (OnTapped);
  }

  public ICommand TapCommand 
  {
    get { return tapCommand; }
  }

  void OnTapped (object s)
  {
    //DO whatever you want
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2021-11-13
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多