Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

ListView OneWay Databinding

$
0
0

I want to do the databinding to a List to a ListView.
I use the "{Binding Nickname}" in the xaml.
When the app runs, there is no items in the ListView.

I only want to fill a Class data to the ListView items.
The items is ok with read only, not need TwoWay Mode.

I want to show the 4 elem on one item line:
ChatMessage.Nickname
ChatMessage.Ip
ChatMessage.Message
ChatMessage.MessageNumber

---- MainPage.xaml ----

    <ListView x:Name="listView" ItemsSource="{Binding chatMessages}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                        <StackLayout Padding="5,0,0,0" VerticalOptions="StartAndExpand" Orientation="Vertical">
                        <Label x:Name="nickname" Text="{Binding Nickname}" VerticalTextAlignment="Center" FontSize="Medium" />
                            <Label Text="{Binding Message}" VerticalTextAlignment="Center" FontSize="Small" />
                        </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

---- MainPage.xaml.cs ----

public partial class MainPage : ContentPage
{
    public IList<ChatMessage> chatMessages;

    public MainPage()
    {
        InitializeComponent();

        chatMessages = new List<ChatMessage>();
        for (int i = 0; i < 100; i++)
        {
            var msg = new ChatMessage();
            msg.Nickname = "Nickname01";
            msg.Ip = "127.0.0.1";
            msg.Message = "Message01";
            msg.MessageNumber = 49;
            chatMessages.Add(msg);
        }

        this.BindingContext = chatMessages;
    }
}

---- ChatMessage.cs ----

public class ChatMessage
{
    public string Nickname { get; set; }
    public string Ip { get; set; }
    public string Message { get; set; }
    public int MessageNumber { get; set; }
}

Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>