按代码选择TextCell不会突出显示行

时间:2017-11-26 16:02:34

标签: c# xamarin xamarin.forms

当我在ListView中单击TextCell时,该行会突出显示。

但是,当我以编程方式选择一行/一个TextCell时,该行不会突出显示。

因此,除非他通过点击一行来更改选择,否则无法向用户指示当前选择了ListView中的哪个值。

这是一个错误或缺少的功能,或者我如何通过代码实现突出显示?

示例代码附于下方。

using MyApp.Model;
using System.Collections.Generic;
using Xamarin.Forms;

namespace MyApp
{
    public class IntSelector : ContentPage
    {
        private ListView m_ListView;

        public IntSelector(int uSelectedInt)
        {
            DataTemplate nTemplate = new DataTemplate(typeof(TextCell));

            // We can set data bindings to our supplied objects.
            nTemplate.SetBinding(TextCell.TextProperty, "String");
            nTemplate.SetBinding(TextCell.DetailProperty, "Int");

            List<clsStringInt> nList = new List<clsStringInt>();

            clsStringInt nItem1 = new clsStringInt { String = "German", Int = 1031 };
            clsStringInt nItem2 = new clsStringInt { String = "English", Int = 1033 };
            clsStringInt nItem3 = new clsStringInt { String = "Spanish", Int = 1034 };

            nList.Add(nItem1);
            nList.Add(nItem2);
            nList.Add(nItem3);

            m_ListView = new ListView();
            m_ListView.ItemTemplate = nTemplate;
            m_ListView.ItemsSource = nList;

            m_ListView.ItemSelected += this.OnSelection;

            m_ListView.SelectedItem = nItem2;//this triggers the "OnSelection" event, so it works
            nItem2.String = "->> " + nItem2.String; //the item's new string is display in the ListView, so that works as well
            //what DOESN'T work is the highliting

            this.Content = m_ListView;
        }

        void OnSelection(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null)
            {
                return; //ItemSelected is called on deselection, which results in SelectedItem being set to null
            }

            clsStringInt n = (clsStringInt)e.SelectedItem;
            string sSelectedIntAsString = n.Int.ToString();

            DisplayAlert("Item Selected", sSelectedIntAsString, "Ok");
        }

    }
}

namespace MyApp.Model
{
    public class clsStringInt
    {
        public string String { get; set; }
        public int Int { get; set; }
    }
}

1 个答案:

答案 0 :(得分:1)

正如你在UWP Forms应用程序中评论的评论所述,这似乎是该平台上的一个错误,看它在Android和iOS上是如何工作的。

我能够通过在OnAppearing而不是在页面构造函数中设置所选项来解决此问题,以使其突出显示。