ListView의 내용을 동적으로 갱신하고 싶은 경우는 ObservableCollection를 이용한다

6361 단어 XamarinC#
예를 들면 이런 View(ChatPage.xaml)가 있고,
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MessageApp.Views.ChatPage">
    <ContentPage.Content>
        <StackLayout>
            <ListView x:Name="messagesView" VerticalOptions="FillAndExpand"></ListView>
            <StackLayout Orientation="Vertical" VerticalOptions="End">
                <Entry x:Name="message" Placeholder="Write something here..." Keyboard="Chat" />
                <Button Text="Send" WidthRequest="80" Clicked="OnSendTapped" />
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>


이런 동작을 기대하고 있을 때,



이런 식의 View(ChatPage.xaml.cs)를 써도 기대한 동작은 되지 않는다.
using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace MessageApp.Views
{
    public partial class ChatPage : ContentPage
    {
        private List<string> messages = new List<string>();

        public ChatPage()
        {
            InitializeComponent();
            Title = "Message";
            messagesView.ItemsSource = messages;
        }

        void OnSendTapped(object sender, EventArgs args)
        {
            messages.Add(message.Text);
            message.Text = "";
        }
    }
}


List의 객체를 ItemSource로 지정해도, ListView측이 변경을 검지할 수 없기 때문에, 변경을 검지시키고 싶은 경우는 ObservableCollection를 이용할 필요가 있다. 수정 후의 코드가 이쪽.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xamarin.Forms;

namespace MessageApp.Views
{
    public partial class ChatPage : ContentPage
    {
        private ObservableCollection<string> messages = new ObservableCollection<string>();

        public ChatPage()
        {
            InitializeComponent();
            Title = "Message";
            messagesView.ItemsSource = messages;
        }

        void OnSendTapped(object sender, EventArgs args)
        {
            messages.Add(message.Text);
            message.Text = "";
        }
    }
}

참고 : ListView Data Sources: Data Binding

좋은 웹페이지 즐겨찾기