在 Xamarin 中填充和更新 ListView

Populating and updating a ListView in Xamarin

我只想用数据填充 Xamarin 中的 ListView 并更新它,以便项目可见。现在我搜索了很多并尝试了这个:

    List<string> items = new List<string> ();
    ArrayAdapter ListAdapter = null;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.Main);

        Button button = FindViewById<Button>(Resource.Id.MyButton);
        ListView listView = FindViewById<ListView>(Resource.Id.listView1);

        ListAdapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItem1, items);
        listView.Adapter = ListAdapter;

        button.Click += delegate { Server(listView); };
    }

现在方法 'Server' 有以下代码:

 items.Add("The server is running at port localEndPoint...");                
 ListAdapter.NotifyDataSetChanged();

这绝对没有任何作用。什么都没有更新。我也试过:

 RunOnUiThread(() =>
 {
   ListAdapter.NotifyDataSetChanged();
 });

但这里甚至没有跳入RunOnUiThread。

我做错了什么?我对 Xamarin 很陌生。

更新:完整服务器代码:

  try
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

            /* Initializes the Listener */
            TcpListener myList = new TcpListener(ipAddress, 8001);

            /* Start Listeneting at the specified port */
            myList.Start();

            ListAdapter.Add("The server is running at port localEndPoint...");
            RunOnUiThread(() =>
            {
                ListAdapter.NotifyDataSetChanged();
            });

            Console.WriteLine("The local End point is  :" +
                              myList.LocalEndpoint);
            Console.WriteLine("Waiting for a connection.....");

            Socket s = myList.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

            byte[] b = new byte[100];
            int k = s.Receive(b);
            Console.WriteLine("Recieved...");
            for (int i = 0; i < k; i++)
                Console.Write(Convert.ToChar(b[i]));

            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");
            /* clean up */
            s.Close();
            myList.Stop();

        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }

您需要将项目添加到 ArrayAdapter 本身:

 ListAdapter.Add("The server is running at port localEndPoint...");        
 ListAdapter.NotifyDataSetChanged();

如果您的代码在后台线程上运行,您需要将其包装在 RunOnUiThread 中,正如您在问题中提到的那样。