当前位置: 首页 > news >正文

适用于初学者的 .NET MAUI

适用于初学者的 .NET MAUI | Microsoft Learn

记录微软Learn中用到的代码。文章比较粗糙,大部分是项目代码粘贴。想详细学习的可到上面的链接学习,代码可以从这里复制后直接运行。

练习中一共有两个页面:

1、MainPage.xaml 用于添加列表中的内容。主要功能有向列表中添加一项;左滑删除该项;点击该选项进入详情页面。

2、DetailPage.xaml 显示详细信息,实际上显示的很少。返回主界面。

用到的MVVM包有:

1、CommunityToolkit.Mvvm

接下来是MainPage.xaml代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="MauiAppDemo1.MainPage"xmlns:viewmode="clr-namespace:MauiAppDemo1.ViewModel"x:DataType="viewmode:MainViewModel"><Grid RowDefinitions="100,Auto,*"ColumnDefinitions=".75*,.25*"Padding="10"RowSpacing="10"ColumnSpacing="10"><Image Grid.ColumnSpan="2"Source="dotnet_bot.png"Background="white"/><Entry Placeholder="Enter task"Text="{Binding Text}"Grid.Row="1"/><Button Text="Add"Command="{Binding AddCommand}"Grid.Row="1"Grid.Column="1"/><CollectionView Grid.Row="2" Grid.ColumnSpan="2"ItemsSource="{Binding Items}"SelectionMode="None"><!--<CollectionView.ItemsSource><x:Array Type="{x:Type x:String}"><x:String>Apples</x:String><x:String>Bananas</x:String><x:String>Oranges</x:String></x:Array></CollectionView.ItemsSource>--><CollectionView.ItemTemplate><DataTemplate x:DataType="{x:Type x:String}"><SwipeView><SwipeView.RightItems><SwipeItems>    <SwipeItem Text="Delete"BackgroundColor="Red"Command="{Binding Source={RelativeSource AncestorType={x:Type viewmode:MainViewModel}},Path=DeleteCommand}"CommandParameter="{Binding .}"/></SwipeItems></SwipeView.RightItems><Grid Padding="0,5"><Frame><Frame.GestureRecognizers><TapGestureRecognizer Command="{Binding Source={RelativeSource AncestorType={x:Type viewmode:MainViewModel}},Path=TapCommand}"CommandParameter="{Binding .}"/></Frame.GestureRecognizers><Label Text="{Binding .}"FontSize="24"/></Frame></Grid></SwipeView></DataTemplate></CollectionView.ItemTemplate></CollectionView></Grid></ContentPage>
using MauiAppDemo1.ViewModel;namespace MauiAppDemo1;public partial class MainPage : ContentPage
{int count = 0;public MainPage(MainViewModel vm){InitializeComponent();BindingContext = vm;}}
    using MauiAppDemo1.ViewModel;namespace MauiAppDemo1;public static class MauiProgram
{public static MauiApp CreateMauiApp(){var builder = MauiApp.CreateBuilder();builder.UseMauiApp<App>().ConfigureFonts(fonts =>{fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");});builder.Services.AddSingleton<MainPage>();builder.Services.AddSingleton<MainViewModel>();builder.Services.AddTransient<DetailPage>();builder.Services.AddSingleton<DetailViewModel>();		return builder.Build();}
}
namespace MauiAppDemo1;public partial class AppShell : Shell
{public AppShell(){InitializeComponent();Routing.RegisterRoute(nameof(DetailPage),typeof(DetailPage));}
}
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace MauiAppDemo1.ViewModel
{/// <summary>/// CommunityToolkit.Mvvm/// </summary>public partial class MainViewModel : ObservableObject{public MainViewModel(){items = new ObservableCollection<string>();}[ObservableProperty]ObservableCollection<string> items;[ObservableProperty]string text;[RelayCommand]void Add(){if (string.IsNullOrWhiteSpace(Text)) return;items.Add(Text);Text = string.Empty;}[RelayCommand]void Delete(string s){if (items.Contains(s)){items.Remove(s);}}[RelayCommand]  async Task Tap(string s){await Shell.Current.GoToAsync($"{nameof(DetailPage)}?Text={s}");}}/// <summary>/// 基本写法/// </summary>//public class MainViewModel : INotifyPropertyChanged//{//    string text;//    public string Text//    {//        get => text;//        set//        {//            text=value;//            OnPropertyChanged(nameof(Text));//        }//    }//    public event PropertyChangedEventHandler PropertyChanged;//    void OnPropertyChanged(string name)=>PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));//}
}

DetailPage.xaml

                

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="MauiAppDemo1.DetailPage"xmlns:viewmodel="clr-namespace:MauiAppDemo1.ViewModel"x:DataType="viewmodel:DetailViewModel"Title="DetailPage"><VerticalStackLayout Padding="20"><Label Text="{Binding Text}"FontSize="25"VerticalOptions="Center" HorizontalOptions="Center" /><Button Text="Go Back"Command="{Binding GoBackCommand}"/></VerticalStackLayout>
</ContentPage>
using MauiAppDemo1.ViewModel;namespace MauiAppDemo1;public partial class DetailPage : ContentPage
{public DetailPage(DetailViewModel vm){InitializeComponent();BindingContext = vm;}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;namespace MauiAppDemo1.ViewModel
{[QueryProperty("Text","Text")]public partial class DetailViewModel:ObservableObject{[ObservableProperty]string text;[RelayCommand]async Task GoBack(){await Shell.Current.GoToAsync("..");}}
}

http://www.lryc.cn/news/227221.html

相关文章:

  • Web3项目灵魂所在之智能合约编写(Web3项目一实战之二)
  • python-jupyter实现OpenAi语音对话聊天
  • 恒源云之oss上传数据、云台下载数据
  • 大数据-之LibrA数据库系统告警处理(ALM-12039 GaussDB主备数据不同步)
  • 【左程云算法全讲6】链表相关
  • 从HDFS到对象存储,抛弃Hadoop,数据湖才能重获新生?
  • 灰度与二值化
  • No183.精选前端面试题,享受每天的挑战和学习
  • [C国演义] 第十八章
  • 发送失败的RocktMQ消息,你遇到过吗?
  • Unity中全局光照GI的总结
  • 毫米波雷达技术在自动驾驶中的关键作用:安全、精准、无可替代
  • Jetson平台180度鱼眼相机畸变校正调试记录
  • axios请求的问题
  • 【pandas刷题系列】Leetcode Problem: [595. 大的国家]
  • 【打卡】牛客网:BM46 最小的K个数
  • Android各类View触摸监听器失效
  • 未整理的知识链接
  • 【2011年数据结构真题】
  • 【科研绘图】MacOS上的LaTeX公式插入工具——LaTeXiT
  • 仓库自动化中的RFID技术的应用浅谈
  • 容器网络-Underlay和Overlay
  • 基于FPGA的PCIe-Aurora 8/10音频数据协议转换系统设计阅读笔记
  • stm32控制舵机sg90
  • state 和 props 有什么区别?
  • Unity 获取桌面路径的方法
  • 基于SSM的考研图书电子商务平台的设计与实现
  • 信息系统“好用”的标准探讨
  • vue elementui 实现从excel从复制多行多列后粘贴到前端界面el-table
  • C++学习 --类和对象之友元