C# 如何在ListView中获得点击的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13326583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:12:51  来源:igfitidea点击:

How to get clicked item in ListView

c#xamlwindows-8

提问by Ixx

This should be a trivial Task but I can't find how to do it. I want to listen to a click on an item in a listview, get the corresponding model object, and launch a new screen.

这应该是一项微不足道的任务,但我找不到如何去做。我想听听单击列表视图中的项目,获取相应的模型对象,然后启动一个新屏幕。

This is the XAML for the ListView:

这是 ListView 的 XAML:

<ListView x:Name="ItemListView" 
    ItemTemplate="{StaticResource StoreFrontTileTemplate}"
    ItemContainerStyle="{StaticResource StoreFrontLVTileStyle}"
    Margin="0" VerticalAlignment="Top" ItemClick="MyClick" Tapped="MyTap"/>

And MyClick, MyTap:

和 MyClick、MyTap:

private void MyClick(object sender, ItemClickEventArgs e)
{
    Debug.WriteLine("Click!");
}

private void MyTap(object sender, TappedRoutedEventArgs e)
{
    Debug.WriteLine("TAp!!" + sender.ToString() + "--" + e.ToString());
}

The method to navigate to the new screen:

导航到新屏幕的方法:

this.Frame.Navigate(typeof(SecondScreen));

It works, but I need the model object of the clicked item and pass it as a Parameter to the second screen.

它有效,但我需要单击项目的模型对象并将其作为参数传递给第二个屏幕。

But MyClick is never called, and MyTap doesn't give me any Information about the clicked item. "sender" is the ListView.

但是 MyClick 永远不会被调用,而且 MyTap 没有给我任何关于被点击项目的信息。“发件人”是 ListView。

I downloaded these exaples:

我下载了这些例子:

http://code.msdn.microsoft.com/windowsapps/XAML-ListView-sample-pack-0ec6b60f

http://code.msdn.microsoft.com/windowsapps/XAML-ListView-sample-pack-0ec6b60f

But it doesn't contain what I need, there's a master / detail view, but it works with bindings and what I want to do is launch a complete new screen.

但它不包含我需要的东西,有一个主/细节视图,但它与绑定一起工作,我想做的是启动一个完整的新屏幕。

Note: I'm a noob in Windows development and orienting to the usual way to do it in Android or IOS where you implement a callback with the position of the clicked element. No idea about the right way to do it in Windows 8.

注意:我是 Windows 开发中的菜鸟,并且面向在 Android 或 IOS 中执行此操作的常用方法,您可以在其中使用单击元素的位置实现回调。不知道在 Windows 8 中执行此操作的正确方法。

采纳答案by nemesv

You can use the SelectionChangedevent:

您可以使用该SelectionChanged事件:

<ListView x:Name="ItemListView" SelectionChanged="MySelectionChanged" />

And you can get the selected/deseleted items from the SelectionChangedEventArgse.g.:

您可以从SelectionChangedEventArgs例如:

private void MySelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Debug.WriteLine("Selected: {0}", e.AddedItems[0]);
}

Or if you don't need the selection functionality and what to use the ItemClick="MyClick"you need to set IsItemClickEnabledto true:

或者,如果您不需要选择功能和使用什么,ItemClick="MyClick"您需要设置IsItemClickEnabledtrue

Gets or sets a value that indicates whether items in the view raise an ItemClick event in response to interaction.

获取或设置一个值,该值指示视图中的项目是否引发 ItemClick 事件以响应交互。

<ListView x:Name="ItemListView" 
    ItemTemplate="{StaticResource StoreFrontTileTemplate}"
    ItemContainerStyle="{StaticResource StoreFrontLVTileStyle}"
    Margin="0" VerticalAlignment="Top" ItemClick="MyClick"  
    IsItemClickEnabled="bool" SelectionMode="None"/>

Note that in this case you also need to set the SelectionModeto None.

请注意,在这种情况下,您还需要SelectionModeNone.

回答by Ngoc Nguyen

You can use DoubleTappedevent of listview on XAML code. And then, in C# code you can get position by:

您可以在 XAML 代码上使用列表视图的DoubleTapped事件。然后,在 C# 代码中,您可以通过以下方式获得位置:

private void display_DoubleTapped_1(object sender,
     Windows.UI.Xaml.Input.DoubleTappedRoutedEventArgs e)
{
     int items = display.SelectedIndex;
     // use this index to do something 
}

回答by Matthias Herrmann

I use this:

我用这个:

private void ListUI_Tapped(object sender, TappedRoutedEventArgs e)
    {
        if(ListUI.SelectedItems.Count != 0)
        {
            Debug.WriteLine("It's not a trap at all my friend");
        }
        else
        {
            Debug.WriteLine("Its a trap");
        }
    }

回答by Rajesh-Systematix

       // We have a class name 'Message' in ControllerLibrary Namespace

         namespace ControllerLibrary
            {
              public class Message
                {
                   public string MessageID { get; set; }
                    public string MessageName { get; set; }
                 }
            }

    // Add name space at page heading
               xmlns:local1="using:ControllerLibrary"

      //At Gridview 

        <GridView IsItemClickEnabled="True" Name="UserMessageList">
         <GridView.ItemTemplate>
           <DataTemplate x:DataType="local1:Message">                                          <StackPanel Orientation="Horizontal">
         <Button Content="{x:Bind MessageName}" HorizontalAlignment="Left" Margin="2 0 10 0" Click="btnUserMessage_Click">
        </Button>
        </StackPanel>
        </DataTemplate>
         </GridView.ItemTemplate>
        </GridView>

  //At code Behind
    private void btnAddPage_Click(object sender, RoutedEventArgs e)
      {
          //Get selecte message
          var selectedMessage = (sender as Button).DataContext as Message;
      }

回答by Varus Septimus

I would suggest that, in the code-behind C# file associated to the XAML, you use the ClickedItemproperty of the ItemClickEventArgsobject passed as argument to the ItemClickevent handler.

我建议,在与 XAML 关联的代码隐藏 C# 文件中,您使用作为参数传递给ItemClick事件处理程序的ItemClickEventArgs对象的ClickedItem属性。

Example (for a GridView, but it's the same idea for a ListView):

示例(对于 GridView,但对于 ListView 是相同的想法)

private void GridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // This is how you determine the clicked item in a GridView,
            // and obtain the relevant element of the underlying collection
            // (to which the GridView is bound).
            // 'Tile' is here the 'type' used in the said collection.
            Tile output = e.ClickedItem as Tile;

            // ... 

        }