You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin.Forms中将两个XAML及XAML.cs文件绑定到同一个ViewModel?

如何将两个XAML文件绑定到同一个ViewModel实例

当然可以实现,下面是几种常用的可行方案:

1. 共享ViewModel单例实例

手动创建ViewModel的单例,然后给两个XAML页面的DataContext统一赋值这个实例。

示例代码:

// ViewModel类(需实现INotifyPropertyChanged保证UI同步)
public class SharedViewModel : INotifyPropertyChanged
{
    private string _sharedContent;
    public string SharedContent
    {
        get => _sharedContent;
        set
        {
            _sharedContent = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

// 单例容器类
public static class ViewModelHolder
{
    public static SharedViewModel Instance { get; } = new SharedViewModel();
}

// 第一个页面后台代码
public partial class PageA : Page
{
    public PageA()
    {
        InitializeComponent();
        DataContext = ViewModelHolder.Instance;
    }
}

// 第二个页面后台代码
public partial class PageB : Page
{
    public PageB()
    {
        InitializeComponent();
        DataContext = ViewModelHolder.Instance;
    }
}

XAML中直接绑定属性:

<!-- PageA.xaml -->
<TextBlock Text="{Binding SharedContent}" />

<!-- PageB.xaml -->
<TextBox Text="{Binding SharedContent, Mode=TwoWay}" />

2. 应用级静态资源共享

在App.xaml中定义ViewModel的静态资源,两个页面直接引用该资源作为DataContext,资源默认是单实例的。

示例:

<!-- App.xaml -->
<Application.Resources>
    <local:SharedViewModel x:Key="GlobalSharedVM" />
</Application.Resources>

<!-- PageA.xaml -->
<Page DataContext="{StaticResource GlobalSharedVM}">
    <TextBlock Text="{Binding SharedContent}" />
</Page>

<!-- PageB.xaml -->
<Page DataContext="{StaticResource GlobalSharedVM}">
    <TextBox Text="{Binding SharedContent, Mode=TwoWay}" />
</Page>

3. 依赖注入(DI)单例注册

如果使用DI框架(如Prism、Microsoft.Extensions.DependencyInjection),将ViewModel注册为单例,页面构造函数中注入该实例即可。

示例(基于Microsoft.Extensions.DependencyInjection):

// 注册单例ViewModel
var services = new ServiceCollection();
services.AddSingleton<SharedViewModel>();
var serviceProvider = services.BuildServiceProvider();

// 页面构造函数注入
public partial class PageA : Page
{
    public PageA(SharedViewModel vm)
    {
        InitializeComponent();
        DataContext = vm;
    }
}

public partial class PageB : Page
{
    public PageB(SharedViewModel vm)
    {
        InitializeComponent();
        DataContext = vm;
    }
}

注意:所有方案中,ViewModel必须实现INotifyPropertyChanged接口,才能确保属性变更时两个页面的UI同步更新。

内容的提问来源于stack exchange,提问作者Jace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:09:28