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

UWP技术问题:如何复制包含WebView2内容的PivotItem

解决方案

修改后的MainPage.xaml.cs代码

private void addButton_Click(object sender, RoutedEventArgs e)
{
    // 创建新的PivotItem
    var newPivotItem = new PivotItem();
    newPivotItem.Header = $"New Tab {pivot.Items.Count + 1}";

    // 创建承载WebView2的Grid容器
    var grid = new Grid();

    // 实例化新的WebView2控件
    var newWebView = new WebView2();
    newWebView.Margin = new Thickness(-12, 0, -12, 0);
    newWebView.Source = new Uri("https://example.com");

    // 绑定与原WebView2相同的事件处理逻辑
    newWebView.NavigationStarting += webView2_NavigationStarting;
    newWebView.NavigationCompleted += webView2_NavigationCompleted;

    // 将WebView2添加到Grid,再绑定到PivotItem
    grid.Children.Add(newWebView);
    newPivotItem.Content = grid;

    // 添加新标签并自动切换到该标签
    pivot.Items.Add(newPivotItem);
    pivot.SelectedItem = newPivotItem;
}

private void removeButton_Click(object sender, RoutedEventArgs e)
{
    if (pivot.SelectedItem is PivotItem selectedItem)
    {
        // 清理WebView2资源,避免内存泄漏
        if (selectedItem.Content is Grid grid && grid.Children[0] is WebView2 webView)
        {
            webView.Dispose();
        }
        pivot.Items.Remove(selectedItem);
    }

    // 无标签页时退出程序
    if (pivot.Items.Count == 0)
    {
        Application.Current.Exit();
    }
}

核心说明

  • 不能直接复用原WebView2控件:每个UI控件只能属于一个父容器,必须创建新的WebView2实例才能添加到新标签页。
  • 同步配置:新WebView2需复制原控件的Margin、默认Source,并绑定相同的事件处理方法,保证功能一致。
  • 资源清理:移除标签时手动释放WebView2资源,防止内存泄漏。
  • 标签命名:通过pivot.Items.Count + 1生成唯一的标签标题,避免重复。

原XAML代码无需修改

你提供的MainPage.xaml代码可以保持原样,初始PivotItem的WebView2配置已作为模板参考。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:39:19