首先吧,我们建立俩文件夹,一个叫Views,一个叫ViewModels。这两文件夹的作用,Views是为了放页面文件(xmal),ViewModels是为了放负责后台处理功能的文件。然后把MainPage.xaml放到Views中,就直接拖就行。
下面就是项目生成的时候自带的MainPage.xaml文件,我把其中没用的都给删除了。其中{Binding a}就是数据绑定的语句,"Binding"是固有的,"a"是我们定义的变量名,外边用{}给括上。
<?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="MauiApp3_测试MVVM_.MainPage"> <StackLayout> <Label Text="{Binding a}"/> </StackLayout> </ContentPage>
然后我们就该去在它对应的MainPage.xaml.cs文件中创建与ViewModel文件的连接了。哦对了,我们还要在ViewModels文件夹中建立一个MainPageViewModel.cs的ViewModel文件
using MauiApp3_测试MVVM_.ViewModels; namespace MauiApp3_测试MVVM_ { public partial class MainPage : ContentPage { int count = 0; public MainPage() { InitializeComponent(); BindingContext = new MainPageViewModel(); // 这一句就是连接用的,然后别忘了上面要using一下ViewModels文件夹 } } }
最后就是在MainPageViewModel.cs中创建要绑定的数据了
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MauiApp3_测试MVVM_.ViewModels { internal class MainPageViewModel:BindableObject { private string _a { get; set; } // 这是变量 public string a // 这是属性,一般都不直接定义变量,都设置个属性给这个变量,然后去定义这个属性,为了保证数据安全 { get => _a; // lambda函数,相当于 return _a; // 这里的判断是为了确保不无限循环的给属性 a 赋值,当变量 _a 不等于新传入的值的时候,再把这个值传递给属性 a 。 set { if (value != _a) { _a = value; OnPropertyChanged(nameof(a)); } } } public MainPageViewModel() { a = "Hello World!"; } } }
这是最后的输出结果:
源码下载:
链接:https://pan.baidu.com/s/10khLymehDvzrEFbF_Eqs4g
提取码:p05x
--来自百度网盘超级会员V6的分享

