[英]Force WPF Immediate UI update from UI thread
(注意:我能找到的與“強制 WPF UI 更新”相關的每個問題似乎都是關於從后台線程觸發一個問題。這不是我想要的;我所有的代碼都在UI 線程中。)
我的視圖模型命令處理程序更改了綁定到TextBlock
的Visibility
的公共布爾Failed
屬性。 這使得綁定的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 強制它處理所有屬性更改,在我繼續之前進行布局和渲染? 或者也許我可以連接某種類型的“更新完成”事件?
目前我正在使用一個對我來說看起來很糟糕的hack:我使命令處理程序異步並在我編寫代碼之前使用這個,在繼續編寫之前使用任意背景延遲
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);
但在我看來,這似乎不是一個非常可靠的方法。 有更好的嗎?
在截屏之前調用這個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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.