I'm building an app that needs the Entry field a Button and a ListView, so when I type something in the entry field and click the button, the field entered passes to the List View. Does anyone have an example that I can rely on?
Thanks in advance
so when I type something in the entry field and click the button, the field entered passes to the List View.
First , you can refer to this official document to create a ListView with Data binding.Then adding Button and Entry to layout,last you can deal with adding data by button click event.
The employee class:
public class Employee{
public string DisplayName {get; set;}
}
The DataModel Class:
public class DataModel
{
public ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
public DataModel()
{
employees.Add(new Employee { DisplayName = "Rob Finnerty" });
employees.Add(new Employee { DisplayName = "Bill Wrestler" });
employees.Add(new Employee { DisplayName = "Dr. Geri-Beth Hooper" });
employees.Add(new Employee { DisplayName = "Dr. Keith Joyce-Purdy" });
employees.Add(new Employee { DisplayName = "Sheri Spruce" });
employees.Add(new Employee { DisplayName = "Burt Indybrick" });
}
}
The following snippet demonstrates a ListView
bound to a list of employees,adding Button
and Entry
.When clicking button,text from Entry
will add to ListView
:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App1"
x:Class="App1.MainPage">
<StackLayout BackgroundColor="Gray">
<!-- Place new controls here -->
<Entry x:Name="EntryText" Placeholder="input"/>
<Button Text="click me"
HorizontalOptions="Center"
VerticalOptions="Center"
Clicked="OnButtonClicked"/>
<ListView x:Name="EmployeeView">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding DisplayName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
Finally ContentPage
will deal with Click Event:
DataModel dataModel;
public MainPage()
{
InitializeComponent();
dataModel = new DataModel();
EmployeeView.ItemsSource = dataModel.employees;
}
void OnButtonClicked(object sender, EventArgs args)
{
Console.WriteLine("click me");
dataModel.employees.Add(new Employee { DisplayName = EntryText.Text });
}