Xamarin与UWP Secondary Window调整大小时内容未同步适配问题
解决方案
- 修正Secondary Window初始化逻辑,新增Xamarin.Forms页面和原生窗口的尺寸绑定逻辑,修改后的代码如下:
static async Task OpenSecondaryWindow(ContentPage contentPage) { var coreApplicationView = CoreApplication.CreateNewView(); int viewId = 0; await coreApplicationView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var frame = new Windows.UI.Xaml.Controls.Frame(); // 将Xamarin.Forms页面渲染为UWP原生元素,避免直接传参导致的布局上下文丢失 var renderer = Xamarin.Forms.Platform.UWP.Platform.CreateRenderer(contentPage); var nativePage = new Windows.UI.Xaml.Controls.Page { Content = renderer.ContainerElement }; frame.Content = nativePage; Window.Current.Content = frame; Window.Current.Activate(); viewId = ApplicationView.GetForCurrentView().Id; // 绑定原生窗口尺寸变化事件,同步触发Xamarin.Forms页面重绘 Window.Current.SizeChanged += (sender, args) => { contentPage.Layout(new Xamarin.Forms.Rectangle(0, 0, args.Size.Width, args.Size.Height)); contentPage.ForceLayout(); }; App.StyleViews(); }); bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(viewId); }
- 检查ContentPage的布局配置:不要给页面或根布局设置固定的
WidthRequest/HeightRequest属性,根布局的HorizontalOptions、VerticalOptions需设置为Fill,优先使用Grid、FlexLayout这类自适应布局容器,避免用AbsoluteLayout写死控件坐标。 - 如果存在自定义尺寸适配逻辑,可以在ContentPage的后台代码中监听自身的
SizeChanged事件,触发时手动更新控件状态:
public YourCustomPage() { InitializeComponent(); SizeChanged += (s, e) => { // 补充自定义适配逻辑 }; }
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

