简体   繁体   English

如何在Xamarin表单的视图中添加和检索列表?

[英]How to add and retrieve lists from a view in Xamarin forms?

I'm making a Xamarin app for android using .net standard 2.0 and I have quite large objects to handle. 我正在使用.net standard 2.0为Android开发Xamarin应用程序,并且我要处理很多对象。 I want to make a few views for them where they are added to a list and then the user can choose from them, then I retrieve the selected object and open a more detailed view. 我想为它们添加一些视图,然后将它们添加到列表中,然后用户可以从中进行选择,然后检索选定的对象并打开一个更详细的视图。

What approach is the best for this? 哪种方法最好呢? So far I have them in a listview with a couple properties stitched together in a string and then I split the selected string and search for the matching object but this seems really prone to breakage as I don't know what value the objects will have until runtime. 到目前为止,我已经将它们放在一个列表视图中,并用字符串将几个属性缝合在一起,然后拆分选定的字符串并搜索匹配的对象,但这似乎真的很容易损坏,因为我不知道这些对象将具有什么值,直到运行。

I'd like to add them to a grid as this seems the best to customise layout wise, is it possible to add these values to a grid and attach a TapGestureRecognizer to the row, and somehow store and receive the selected object of that row? 我想将它们添加到网格中,因为这似乎是自定义布局的最佳方法,是否可以将这些值添加到网格并将TapGestureRecognizer附加到该行,并以某种方式存储和接收该行的选定对象?

If you use ICommand you can simply implement TapGestureRecognizer. 如果使用ICommand,则可以简单地实现TapGestureRecognizer。 First create the GridView in XAML file like this: 首先像这样在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>

after that in c# code setting the binding like this: 之后,在c#代码中设置绑定,如下所示:

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

Then you should implement the command: 然后,您应该执行以下命令:

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
  }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM