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

.NET MAUI Blazor Hybrid桌面应用:调试窗口大小与编写媒体查询

解决.NET MAUI Blazor Hybrid桌面应用的媒体查询调试与实现问题

1. 手动调整窗口测试媒体查询

直接拖动桌面应用的窗口边缘,调整到目标尺寸,配合Blazor的热重载功能,修改CSS后实时查看样式效果。这是最直接的测试方式,无需额外工具。

2. 强制设置窗口初始尺寸(针对特定断点测试)

如果需要固定测试某个尺寸的窗口,可以在对应平台的代码里设置窗口初始大小:

  • Windows平台:打开Platforms/Windows/App.xaml.cs,在OnLaunched方法中添加窗口尺寸设置:
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    base.OnLaunched(args);
    var window = Application.Current.Windows.First();
    window.Width = 1200; // 目标宽度
    window.Height = 800; // 目标高度
}
  • MacCatalyst平台:打开Platforms/MacCatalyst/AppDelegate.cs,在FinishedLaunching方法中设置:
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
    var window = new UIWindow(UIScreen.MainScreen.Bounds);
    window.Frame = new CGRect(0, 0, 1200, 800); // 设置窗口尺寸
    // 其他初始化代码...
    return base.FinishedLaunching(application, launchOptions);
}

修改后重启应用,窗口会固定为设置的尺寸,方便测试对应断点的媒体查询。

3. 正确编写CSS媒体查询

MAUI Blazor Hybrid的CSS媒体查询语法和Web端完全一致,直接按标准写法编写即可。示例:

/* 默认样式 */
.container {
    padding: 20px;
}

/* 窗口宽度小于768px时的样式 */
@media (max-width: 767px) {
    .container {
        padding: 10px;
        font-size: 14px;
    }
}

/* 窗口宽度在768px到1199px之间的样式 */
@media (min-width: 768px) and (max-width: 1199px) {
    .container {
        padding: 15px;
        font-size: 16px;
    }
}

/* 窗口宽度大于等于1200px时的样式 */
@media (min-width: 1200px) {
    .container {
        padding: 20px;
        font-size: 18px;
    }
}

确保你的CSS文件被正确引用到Blazor组件或_Host.cshtml中。

4. 用JS互操作调试窗口尺寸(可选)

如果需要实时查看当前窗口尺寸,可以通过Blazor的JS互操作获取:

  1. 在wwwroot/js目录下创建windowUtils.js,添加代码:
window.getWindowSize = () => {
    return {
        width: window.innerWidth,
        height: window.innerHeight
    };
};
  1. 在_Host.cshtml中引用该脚本:
<script src="js/windowUtils.js"></script>
  1. 在Blazor组件中调用:
@inject IJSRuntime JSRuntime

<button @onclick="GetWindowSize">查看当前窗口尺寸</button>
<p>当前窗口宽度: @windowWidthpx</p>
<p>当前窗口高度: @windowHeightpx</p>

@code {
    private int windowWidth;
    private int windowHeight;

    private async Task GetWindowSize()
    {
        var size = await JSRuntime.InvokeAsync<WindowSize>("getWindowSize");
        windowWidth = size.Width;
        windowHeight = size.Height;
    }

    public class WindowSize
    {
        public int Width { get; set; }
        public int Height { get; set; }
    }
}

点击按钮就能看到当前窗口的宽高,帮助验证媒体查询是否触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:57:15