WinUI应用设置RequestedTheme为Dark时打印预览窗口显示空白求助
WinUI深色主题下打印预览无文本显示问题
我在WinUI应用中实现了打印功能,并将RequestedTheme设置为Dark。但使用深色主题时,打印预览窗口无法显示任何文本;切换为Light主题时,文本显示正常。
打印功能源码
public sealed partial class MainWindow : Window { private PrintDocument _printDoc; private IPrintDocumentSource _printSource; private List<UIElement> _pages = new List<UIElement>(); public MainWindow() { InitializeComponent(); _printDoc = new PrintDocument(); _printSource = _printDoc.DocumentSource; _printDoc.Paginate += OnPaginate; _printDoc.GetPreviewPage += OnGetPreviewPage; _printDoc.AddPages += OnAddPages; } private async void OnPrintClick(object sender, RoutedEventArgs e) { var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this); var printManager = PrintManagerInterop.GetForWindow(hWnd); printManager.PrintTaskRequested += (s, args) => { args.Request.CreatePrintTask("Print Test", t => t.SetSource(_printSource)); }; await PrintManagerInterop.ShowPrintUIForWindowAsync(hWnd); } private void OnPaginate(object sender, PaginateEventArgs e) { _pages.Clear(); var page = new StackPanel { Margin = new Thickness(20) }; page.Children.Add(new TextBlock { Text = "Hello, this is a print test!", FontSize = 24 }); _pages.Add(page); _printDoc.SetPreviewPage(1, page); } private void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e) { _printDoc.SetPreviewPage(e.PageNumber, _pages[e.PageNumber - 1]); } private void OnAddPages(object sender, AddPagesEventArgs e) { foreach (var p in _pages) _printDoc.AddPage(p); _printDoc.AddPagesComplete(); } }
深色主题设置代码
public partial class App : Application { private Window? _window; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.RequestedTheme = ApplicationTheme.Dark; InitializeComponent(); } }
效果对比
- 深色主题:打印预览窗口无文本显示
- 浅色主题:文本显示正常
解决方法
问题根源是打印预览窗口的背景在深色主题下为深色,而动态创建的TextBlock继承了应用深色主题的白色前景色,导致文本与背景对比度为0,无法看见。以下两种方案可解决:
方案1:显式设置文本前景色
创建TextBlock时直接指定前景色为黑色(或其他高对比度颜色):
page.Children.Add(new TextBlock { Text = "Hello, this is a print test!", FontSize = 24, Foreground = new SolidColorBrush(Colors.Black) });
方案2:强制打印页面使用浅色主题
为打印用的StackPanel单独设置浅色主题,脱离应用主题影响:
var page = new StackPanel { Margin = new Thickness(20), RequestedTheme = ElementTheme.Light };
两种方案都能确保打印预览及实际打印的内容正常显示。
内容的提问来源于stack exchange,提问作者Swetha
相关产品推荐
相关产品推荐

