在listview中获取所选项目

时间:2016-04-13 07:56:20

标签: c# xamarin.forms

我有一个带有标签的列表视图和使用taplate viewcell创建的图像。点击图片我想重定向到新页面说B页并显示项目的详细信息。

image

以下是代码:

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();
        }
    }
}

我尝试添加GestureRecognizers ontap,但如果在图像之外的任何地方点击列表视图,则getselection会返回项目列表。

任何帮助?

修改

我也试过添加这样的东西:

                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");
                });

但它不起作用。得到错误:

System.InvalidCastException: Specified cast is not valid.

3 个答案:

答案 0 :(得分:1)

您可以通过将isEnabled属性设置为false来禁用列表视图选择。这将使listview无法点击,而ViewCell上的GestureRecognizers将按预期响应

For Navigation this can be of help

答案 1 :(得分:0)

使用ListView的ItemHapped的EventHandler然后在代码隐藏中,你应该能够通过将对象参数从ListView转换为期望的类型来访问该项目。

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

答案 2 :(得分:0)

如果你使用包含你的控件的ListView ItemTemplate,用户可以点击该项目的任何地方(这看起来更方便)。

发件人就是你的ListView 所以你可以试试这个:

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