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

MAUI多窗口应用中如何跨窗口访问并修改控件属性?

MAUI跨窗口操作控件实现方案

问题背景

两年前我基于WPF、XAML和C#开发了一款Windows游戏计分板多窗口应用,包含两个窗口:

  • 操作窗口:放在笔记本屏幕,提供分数增减的操作控件
  • 计分板窗口:通过投影仪扩展桌面展示,面向公众显示分数

在WPF中实现跨窗口控件操作很简单:

  1. 在主窗口代码中声明第二个窗口实例:
public scoreboard1 sboard = new scoreboard1();
  1. 在主窗口按钮点击事件中直接修改另一窗口的文本控件属性:
sboard.txtBlckScoreBoardHTPoints.Text = "btn clicked on main window";

现在转到MAUI开发,已经掌握了创建和打开窗口的基础方法:

var pjScreen = new Window(new screen2());
Application.Current.OpenWindow(pjScreen);

需要MAUI范式下跨窗口访问并操作控件的具体实现示例。当前使用Visual Studio Enterprise 2022(64位)17.5.3版本。


实现方案

方法一:保留窗口实例直接操作控件

和WPF思路类似,需注意MAUI的窗口生命周期管理:

  1. 在主窗口类中声明计分板窗口的全局实例:
private Window _scoreboardWindow;
  1. 在主窗口初始化时创建并打开计分板窗口:
_scoreboardWindow = new Window(new screen2());
Application.Current.OpenWindow(_scoreboardWindow);
  1. 修改计分板窗口(screen2)中控件的访问修饰符为public,之后在主窗口按钮点击事件中直接操作:
if (_scoreboardWindow?.Page is screen2 scoreboardPage)
{
    scoreboardPage.txtBlckScoreBoardHTPoints.Text = "主窗口按钮已点击";
}

方法二:使用MVVM(推荐,符合MAUI设计范式)

直接操作控件不符合MVVM思想,更推荐通过共享数据绑定实现解耦:

  1. 创建共享的分数视图模型类:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;

public class ScoreViewModel : INotifyPropertyChanged
{
    private string _scoreText;
    public string ScoreText
    {
        get => _scoreText;
        set
        {
            _scoreText = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  1. 在App.xaml.cs中注册全局视图模型实例:
public ScoreViewModel SharedScoreVM { get; } = new ScoreViewModel();
  1. 主窗口(操作窗口)通过命令修改视图模型属性:
<!-- 主窗口XAML按钮 -->
<Button Text="更新分数" Command="{Binding UpdateScoreCommand}" />
// 主窗口ViewModel逻辑
public ICommand UpdateScoreCommand => new Command(() =>
{
    (Application.Current as App).SharedScoreVM.ScoreText = "主窗口按钮已点击";
});
  1. 计分板窗口(screen2)绑定全局视图模型:
<!-- 计分板窗口XAML控件 -->
<Label Text="{Binding ScoreText}" FontSize="Large" />
// 计分板窗口构造函数设置绑定上下文
public screen2()
{
    InitializeComponent();
    BindingContext = (Application.Current as App).SharedScoreVM;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:35:13