ListView의 내용을 동적으로 갱신하고 싶은 경우는 ObservableCollection를 이용한다
<?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
Reference
이 문제에 관하여(ListView의 내용을 동적으로 갱신하고 싶은 경우는 ObservableCollection를 이용한다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/mah_lab/items/94ea735b45fe9cfccdbf텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)