在Xamarin中填充和更新ListView

时间:2016-04-27 08:32:35

标签: c# listview xamarin populate

我只想在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);
        }

1 个答案:

答案 0 :(得分:0)

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

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

如果您的代码在后台线程上运行,则需要将其包装在RunOnUiThread中,如您在问题中所述。