如何显示TextCell xamarin的内容?

时间:2017-12-25 18:36:02

标签: c# listview xamarin mvvm xamarin.forms

我需要将点击的TextCell数据显示给标签。我不知道为什么会有错误

  

对象引用未设置为对象的实例

数据来自json文件。 itemSelected总是为null,我不明白这段代码有什么问题。

    ListView listViewJson = new ListView();
                var template = new DataTemplate(typeof(CustomCell));
                listViewJson.ItemTemplate = template;
                listViewJson.RowHeight = 70;
                listViewJson.HeightRequest = 380;
                listViewJson.ItemsSource = rootObject.Result;
                StackLayout.Children.Add(listViewJson);
                listViewJson.ItemSelected += OnItemSelected;



    private void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            try
            {
                // PROBLEM TO FIX

                if (e.SelectedItem !=null)
                {
                    var itemSelected =e.SelectedItem as TextCellList;
                    lblCell.Text = itemSelected.TextItem;
                }

            }
            catch (Exception ex)
            {
                DisplayAlert("Error", ex.Message, "OK");
            }

        }

自定义单元格,用作TextCell代码:

     public CustomCell()
        {
            //instantiate each of our views
            StackLayout cellWrapper = new StackLayout();
            StackLayout titleStack = new StackLayout();
            StackLayout horizontalLayout = new StackLayout();
            Label Tittle = new Label();
            Label Detail = new Label();
            Label Detail2 = new Label();

            //set bindings
            Tittle.SetBinding(Label.TextProperty, "title");
            Detail.SetBinding(Label.TextProperty, "id");
            Detail2.SetBinding(Label.TextProperty, "order");

            //Set properties for desired design
            cellWrapper.BackgroundColor = Color.FromHex("#fff");
            horizontalLayout.Orientation = StackOrientation.Horizontal;
            cellWrapper.Padding = 10;
            //right.HorizontalOptions = LayoutOptions.EndAndExpand;
            Tittle.TextColor = Color.FromHex("#000");
            Detail.TextColor = Color.FromHex("#a59f9f");
            Tittle.FontSize = 20;

            //add views to the view hierarchy
            titleStack.Children.Add(Tittle);
            horizontalLayout.Children.Add(Detail);
            horizontalLayout.Children.Add(Detail2);

            cellWrapper.Children.Add(titleStack);
            cellWrapper.Children.Add(horizontalLayout);

            View = cellWrapper;
        }

TextCellList clas:

public class TextCellList
{
    public string title { get; set; }
    public string id { get; set; }
    public string order { get; set; }
}

0 个答案:

没有答案