0

我有一个具有多个 AppWindows 的 UWP 应用。我想在此 AppWindow 的 MainPage 上显示在 XAML 中定义的通用内容对话框。我尝试设置 XamlRoot,但收到此错误:System.Exception: 'Catastrophic failure cannot change XamlRoot when it has been set'。

这是我的 XAML 代码:

<ContentDialog x:Name="DetailsDialog" x:FieldModifier="public" Title="Details" CloseButtonText="Close" Margin="10,50,-10,-50" Visibility="Collapsed">
        <ScrollViewer x:Name="DetailsScrollViewer" x:FieldModifier="Public">
            <StackPanel x:Name="DetailsPanel" x:FieldModifier="public">
                <Frame x:Name="DetailsContentFrame" x:FieldModifier="public" Padding="0,0,0,0" IsTabStop="True">
                </Frame>
            </StackPanel>
        </ScrollViewer>
    </ContentDialog>

这是 AppWindow 的代码,用于在 AppWindow 上显示 ContentDialog:

            PrintableArea.Children.Remove(ProcedureNotesPanel);
        mainPage.DetailsPanel.Children.Add(ProcedureNotesPanel);
        ProcedureNotesPanel.Visibility = Visibility.Visible;
        mainPage.DetailsDialog.Title = title;
        mainPage.DetailsDialog.Visibility = Visibility.Visible;
        mainPage.DetailsDialog.XamlRoot = null;
        mainPage.DetailsDialog.XamlRoot = ((FrameworkElement)sender).XamlRoot;
        await mainPage.DetailsDialog.ShowAsync();
        ProcedureNotesPanel.Visibility = Visibility.Collapsed;
        mainPage.DetailsPanel.Children.Remove(ProcedureNotesPanel);
        PrintableArea.Children.Add(ProcedureNotesPanel);

我究竟做错了什么?我尝试先将 XamlRoot 设置为 null,但即使这样也会引发相同的异常。

谢谢。

4

1 回答 1

0

经过更多的研究和反复试验,我能够通过创建一个新的 ContentDialog 而不是在 MainPage 上使用现有的 ContentDialog 来实现预期的结果。

public async Task<ContentDialogResult> ShowDialog(FrameworkElement ControlToShow, FrameworkElement target, string Title, string CloseButtonText = "Close", ContentDialogPlacement placement = ContentDialogPlacement.Popup)
    {
        try
        {
            var dialog = new ContentDialog()
            {
                Title = Title,
                CloseButtonText = CloseButtonText,
            };
            var panel = new StackPanel() { Name = "CustomContentDialogPanel" };
            var parent = ((Grid)ControlToShow.Parent);

            parent.Children.Remove(ControlToShow);
            panel.Children.Add(ControlToShow);
            ControlToShow.Visibility = Visibility.Visible;
            dialog.Content = panel;
            dialog.XamlRoot = target.XamlRoot;
            var result = await dialog.ShowAsync(placement);
            panel.Children.Remove(ControlToShow);
            parent.Children.Add(ControlToShow);
            ControlToShow.Visibility = Visibility.Collapsed;

            return result;
        }
        catch (Exception ex)
        {
            return ContentDialogResult.None;
        }
    }
于 2021-02-20T20:35:32.840 回答