简体   繁体   English

获取列表视图中的选定项目

[英]Get selected item inside listview

I have a listview with a label and an image created using taplate viewcell. 我有一个带有标签的listview和一个使用taplate viewcell创建的图像。 On tap of an image I would like to redirect to new page say page B and display details of item tapped. 点击图像后,我想重定向到新页面,例如页面B,并显示所点击项目的详细信息。

图片

Here is the code: 这是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using Xamarin.Forms;

namespace ____
{
    public class SelectMultipleBasePage<T> : ContentPage
    {
        public class WrappedSelection<T> : INotifyPropertyChanged
        {
            public T Item { get; set; }
            bool isSelected = false;
            public bool IsSelected
            {
                get
                {
                    return isSelected;
                }
                set
                {
                    if (isSelected != value)
                    {
                        isSelected = value;
                        PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
                        //                      PropertyChanged (this, new PropertyChangedEventArgs (nameof (IsSelected))); // C# 6
                    }
                }
            }
            public event PropertyChangedEventHandler PropertyChanged = delegate { };
        }
        public class BackGroundColorConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value is bool)
                {
                    if ((bool)value)
                    {
                        return Color.FromHex("#DEE4EA");
                    }
                    else
                    {
                        return Color.White;
                    }
                }
                else
                {
                    return Color.White;
                }
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }

        }

        public class WrappedItemSelectionTemplate : ViewCell
        {
            public WrappedItemSelectionTemplate()
                : base()
            {
                Grid objGrid = new Grid();

                objGrid.RowDefinitions.Add(new RowDefinition
                {
                    Height = new GridLength(1, GridUnitType.Star)
                });

                objGrid.ColumnDefinitions.Add(new ColumnDefinition
                {
                    Width = new GridLength(75, GridUnitType.Absolute),
                });
                objGrid.ColumnDefinitions.Add(new ColumnDefinition
                {
                    Width = new GridLength(1, GridUnitType.Star)
                });
                objGrid.ColumnDefinitions.Add(new ColumnDefinition
                {
                    Width = GridLength.Auto
                });

                //
                // Column 1:-
                Image objImage = new Image();
                objImage.SetBinding(Image.SourceProperty, new Binding("Item.Image"));
                objGrid.Children.Add(objImage, 0, 0);


                // Column 2:-
                StackLayout objStackLayoutCol2 = new StackLayout();
                objGrid.Children.Add(objStackLayoutCol2, 1, 0);

                Label name = new Label()
                {
                    Text = "Name",
                    Style = (Style)Application.Current.Resources["LabelStyle"],
                };
                Label date = new Label()
                {
                    Text = "Date",
                    Style = (Style)Application.Current.Resources["LabelStyleTiny"]
                };
                name.SetBinding(Label.TextProperty, new Binding("Item.Name"));
                date.SetBinding(Label.TextProperty, new Binding("Item.Date"));
                objStackLayoutCol2.Children.Add(name);
                objStackLayoutCol2.Children.Add(date);
                objStackLayoutCol2.Padding = new Thickness(10);


                Image objImageView = new Image();
                objImageView.GestureRecognizers.Add(new TapGestureRecognizer(OnTap));
                objImageView.Source = ImageSource.FromFile("Search.png");
                objGrid.Children.Add(objImageView, 2, 0);

                objGrid.SetBinding(Grid.BackgroundColorProperty, "IsSelected", converter: new BackGroundColorConverter());

                //
                // define context actions
                //
                var moreAction = new MenuItem { Text = "More" };

                moreAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
                moreAction.Clicked += (sender, e) =>
                {
                    var mi = ((MenuItem)sender);
                    //Debug.WriteLine("More Context Action clicked: " + mi.CommandParameter);
                };

                var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true }; // red background
                deleteAction.Icon = Device.OnPlatform("Icons/cancel.png", "cancel.png", "Images/cancel.png");
                deleteAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
                deleteAction.Clicked += (sender, e) =>
                {
                    var mi = ((MenuItem)sender);
                    //Debug.WriteLine("Delete Context Action clicked: " + mi.CommandParameter);
                };

                //
                // add context actions to the cell
                //
                ContextActions.Add(moreAction);
                ContextActions.Add(deleteAction);
                //objGrid.Padding = new Thickness(10);

                StackLayout st = new StackLayout();
                st.Children.Add(objGrid);
                st.Children.Add(new BoxView() { Color = Color.FromHex("#A4B3C1"), WidthRequest = 100, HeightRequest = 1 });


                View = st;


            }

            public static void OnTap(View obj)
            {
               List<T> test= GetSelection();
                MessagingCenter.Send(new RedirectClass.OpenRecordingDetails(), RedirectClass.OpenRecordingDetails.Key);
            }
        }
        public static List<WrappedSelection<T>> WrappedItems = new List<WrappedSelection<T>>();
        public SelectMultipleBasePage(List<T> items)
        {
            WrappedItems = items.Select(item => new WrappedSelection<T>() { Item = item, IsSelected = false }).ToList();
            ListView mainList = new ListView()
            {
                ItemsSource = WrappedItems,
                ItemTemplate = new DataTemplate(typeof(WrappedItemSelectionTemplate)),
            };

            mainList.ItemSelected += (sender, e) =>
            {
                if (e.SelectedItem == null) return;
                var o = (WrappedSelection<T>)e.SelectedItem;
                o.IsSelected = !o.IsSelected;
                ((ListView)sender).SelectedItem = null; //de-select
            };
            Content = mainList;
            mainList.HasUnevenRows = true;


            if (Device.OS == TargetPlatform.WinPhone)
            {   // fix issue where rows are badly sized (as tall as the screen) on WinPhone8.1
                mainList.RowHeight = 40;
                // also need icons for Windows app bar (other platforms can just use text)
                ToolbarItems.Add(new ToolbarItem("All", "check.png", SelectAll, ToolbarItemOrder.Primary));
                ToolbarItems.Add(new ToolbarItem("None", "cancel.png", SelectNone, ToolbarItemOrder.Primary));
            }
            else
            {
               //  mainList.MinimumHeightRequest = 80;
               // mainList.RowHeight = 80;
                ToolbarItems.Add(new ToolbarItem("All", null, SelectAll, ToolbarItemOrder.Primary));
                ToolbarItems.Add(new ToolbarItem("None", null, SelectNone, ToolbarItemOrder.Primary));
            }
        }
        void SelectAll()
        {
            foreach (var wi in WrappedItems)
            {
                wi.IsSelected = true;
            }
        }
        void SelectNone()
        {
            foreach (var wi in WrappedItems)
            {
                wi.IsSelected = false;
            }
        }
        public static List<T> GetSelection()
        {
            return WrappedItems.Where(item => item.IsSelected).Select(wrappedItem => wrappedItem.Item).ToList();
        }
    }
}

I tried adding a GestureRecognizers ontap but getselection returns the list of items if the listview is clicked anywhere other then a image. 我尝试添加ontap的GestureRecognizers,但是如果单击listview而不是图像,则getselection返回项目列表。

Any help? 有什么帮助吗?

Edit 编辑

I also tried adding something like this: 我也尝试添加以下内容:

                Button aButton = new Button { Text = "TestButton" };
                aButton.SetBinding(Button.CommandParameterProperty, new Binding("Item.Name"));
                aButton.Command = new Command<Button>((Button theCellItem) =>
                {
                    var s = theCellItem.ToString();
                    //DisplayAlert("Tadaa", theCellItem.ToString(), "Ok");
                });

But It doesn't work. 但这行不通。 Getting error: 出现错误:

System.InvalidCastException: Specified cast is not valid.

You can disable the list view selection by setting isEnabled property to false .This will make listview unclickable while GestureRecognizers on ViewCell will respond as expected 您可以通过将isEnabled属性设置为false来禁用列表视图选择。这将使列表视图不可单击,而ViewCell上的GestureRecognizers将按预期响应

For Navigation this can be of help 对于导航这可能会有帮助

Use the ListView's EventHandler for ItemTapped then on codebehind you should be able to access the item by casting the object parameter to the expected type from your ListView. 将ListView的EventHandler用于ItemTapped,然后在代码后面,您应该能够通过将对象参数从ListView强制转换为期望的类型来访问该项目。

    private void MyListView_OnItemTapped(object sender, ItemTappedEventArgs e)
    {
        var person = sender as Person;
        Debug.WriteLine($"His name was {person.Name}");
    }

If you use a ListView ItemTemplate containing your control, user can click anywhere on the item (which seems more convenient). 如果您使用包含控件的ListView ItemTemplate,则用户可以在项目上的任何位置单击(这似乎更方便)。

The sender is then your ListView so you may try this: 发件人就是您的ListView,因此您可以尝试以下操作:

ListView listView   = sender as ListView;
Person selectedItem = listView == null ? null : listView.SelectedItem as Person;

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

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