(注意:我能找到的與“強制 WPF UI 更新”相關的每個問題似乎都是關于從后臺執行緒觸發一個問題。這不是我想要的;我所有的代碼都在UI 執行緒中。)
Failed我的視圖模型命令處理程式更改了系結到 aTextBlock的公共布爾屬性Visibility。這使得邊界TextBlock變得可見。這部分都是標準的,WPF 的東西并且作業正常;我的 UI 發生了變化,標簽出現了。
<TextBlock Text="Failed" Visibility="{Binding Failed, Converter="{StaticResource CvtBoolToVisibility}}" Foreground="Red" />
但是我添加了代碼,因此在設定此屬性后立即保存應用程式視窗的螢屏截圖。該代碼會生成完美的螢屏影像。不幸的是,它與我更改屬性之前的螢屏一樣,因為 WPF 還沒有機會呈現更改。
var window = Application.Current.MainWindow ?? throw new InvalidOperationException("No window");
var bm = window.CopyAsBitmap() ?? throw new InvalidOperationException("Unable to copy bitmap");
var pngData = bm.Encode(new PngBitmapEncoder());
File.WriteAllBytes(Path.Combine(SaveFolder, "TestOutput.png"), pngData);
有沒有辦法強制 WPF 強制它處理所有屬性更改,在我繼續之前進行布局和渲染?或者也許我可以連接某種型別的“更新完成”事件?
目前我正在使用一個對我來說看起來很糟糕的黑客:我使命令處理程式異步并在我撰寫代碼之前使用這個,在繼續撰寫之前使用任意背景延遲
await Task.Delay(500).ConfigureAwait(true); // Give WPF a chance to update.
var window = Application.Current.MainWindow ?? throw new InvalidOperationException("No window");
var bm = window.CopyAsBitmap() ?? throw new InvalidOperationException("Unable to copy bitmap");
var pngData = bm.Encode(new PngBitmapEncoder());
await File.WriteAllBytesAsync(Path.Combine(SaveFolder, "TestOutput.png"), pngData);
但在我看來,這似乎不是一個非常可靠的方法。有更好的嗎?
uj5u.com熱心網友回復:
在截屏之前呼叫GridParent.UpdateLayout();這里GridParent可以是父控制元件或像你正在做的那樣Application.Current.MainWindow.UpdateLayout();。
我試過了。它將確保在截屏之前呈現 UI。
另外,我用這種方法截屏。
private void SaveSnap()
{
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap((int) GridParent.ActualWidth, (int) GridParent.ActualHeight, 96, 96,
PixelFormats.Pbgra32);
renderTargetBitmap.Render(GridParent);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
using (Stream fileStream = File.Create("Img.png"))
{
pngImage.Save(fileStream);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/481614.html
