Create a new .NET MAUI
item.cs
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
Create a ViewModel
public class ItemViewModel : INotifyPropertyChanged
{
public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<Item>();
public event PropertyChangedEventHandler PropertyChanged;
public ItemViewModel()
{
// Add sample data
Items.Add(new Item { Id = 1, Name = "Item 1" });
Items.Add(new Item { Id = 2, Name = "Item 2" });
Items.Add(new Item { Id = 3, Name = "Item 3" });
}
// Add an item
public void AddItem(string name)
{
int id = Items.Count + 1;
Items.Add(new Item { Id = id, Name = name });
}
// Update an item
public void UpdateItem(int id, string name)
{
var item = Items.FirstOrDefault(i => i.Id == id);
if (item != null)
{
item.Name = name;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Items)));
}
}
// Delete an item
public void DeleteItem(int id)
{
var item = Items.FirstOrDefault(i => i.Id == id);
if (item != null)
{
Items.Remove(item);
}
}
}
- Create the MainPage.xaml:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp.MainPage"
BackgroundColor="{DynamicResource PageBackgroundColor}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Text="Add Item" Clicked="OnAddItemClicked" />
<ListView x:Name="ItemsListView"
Grid.Row="1"
ItemsSource="{Binding Items}"
SelectionMode="Single"
ItemSelected="OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage>
- Update MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
private ItemViewModel _viewModel;
public MainPage()
{
InitializeComponent();
_viewModel = new ItemViewModel();
BindingContext = _viewModel;
}
private void OnAddItemClicked(object sender, EventArgs e)
{
_viewModel.AddItem($"Item {_viewModel.Items.Count + 1}");
}
private async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem is Item selectedItem)
{
// Clear selection
ItemsListView.SelectedItem = null;
// TODO: Show a dialog for editing or deleting the selected item
// For now, we'll just delete the item
_viewModel.DeleteItem(selectedItem.Id);
}
}
}