方法一:在CS代码中绑定
// MainPage.xaml.cs
public partial class MainPage : ContentPage
{
private readonly IServiceProvider _serviceProvider;
public MainPage(IServiceProvider serviceProvider)
{
InitializeComponent();
_serviceProvider = serviceProvider;
BindingContext = _serviceProvider.GetService<MyViewModel>();
}
}
方法二:使用XAML中x:Static
定义:
public class VMLocator
{
public static T GetRequiredService<T>() where T : class
{
if (App.Current?.Handler.MauiContext == null)
throw new NullReferenceException("App.Current.Handler.MauiContext为空");
return App.Current.Handler.MauiContext.Services.GetRequiredService<T>();
}
public static MainPageViewModel GetMainPageViewModel => GetRequiredService<MainPageViewModel>();
}
绑定1:静态绑定
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vm ="clr-namespace:MauiTest.ViewModel"
x:Class="MauiTest.MainPage"
BindingContext="{x:Static vm:VMLocator.GetMainPageViewModel}"
绑定2:通过资源绑定(注意:通过这个方法时类VMLocator中的GetMainPageViewModel不能定义为静态属性)
定义资源
<?xml version = "1.0" encoding = "UTF-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MauiTest"
xmlns:vm="clr-namespace:MauiTest.ViewModel"
x:Class="MauiTest.App">
<Application.Resources>
<ResourceDictionary>
<vm:VMLocator x:Key="SrcVMLocator"></vm:VMLocator> //定义VMLocator资源
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles/Colors.xaml" />
<ResourceDictionary Source="Resources/Styles/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
绑定资源
<ContentPage.BindingContext>
<Binding Source="{x:StaticResource SrcVMLocator}" Path="GetMainPageViewModel"></Binding>
</ContentPage.BindingContext>
方法三:使用自定义标记扩展
定义:
public class ViewModelLocator : IMarkupExtension
{
public string ViewModelType { get; set; } = "";
public object ProvideValue(IServiceProvider serviceProvider)
{
if (string.IsNullOrEmpty(ViewModelType))
throw new ArgumentException("ViewModelType cannot be null or empty.");
var type = Type.GetType(ViewModelType);
if (type == null)
throw new ArgumentException($"Type {ViewModelType} not found.");
var viewModel = App.Current.Handler.MauiContext.Services.GetService(type);
return viewModel;
}
}
绑定:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vm ="clr-namespace:MauiTest.ViewModel"
x:Class="MauiTest.MainPage"
BindingContext="{vm:ViewModelLocator ViewModelType=MauiTest.ViewModel.MainPageViewModel}"
方法一及方法三在xaml进行属性绑定时无提示问题解决方案
方法一:使用 x:DataType 指令
x:DataType 指令可以帮助XAML编辑器识别绑定的类型,从而提供智能提示。
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vm ="clr-namespace:MauiTest.ViewModel"
x:Class="MauiTest.MainPage"
x:DataType="vm:MainPageViewModel"
>