1
我有一個從Canvas繼承的類DottedCanvas的自定義控件,它包含從TextBox繼承的類TreeNode的一些自定義控件。畫布控件風格:WPF:將畫布內容繪製爲位圖問題
<Style x:Key="DottedStyle" TargetType="TreeBuilder:DottedCanvas">
<!--Makes canvas dotted-->
<Setter Property="Background" Value="{StaticResource DottedBrush}"/>
<Style.Triggers>
<Trigger Property="DottedEnabled" Value="False">
<!--Removes dots when printing-->
<Setter Property="Background" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
的TextBox控件被包裝到一個用戶控件,也有自己的風格:
<Style x:Key="NodeBoxStyle" TargetType="{x:Type TreeBuilder:TreeNodeBox}">
<Setter Property="BorderThickness" Value="1"/>
<Style.Triggers>
<!--Must remove d-->
<Trigger Property="IsBeingPrinted" Value="true">
<Setter Property="BorderThickness" Value="0"/>
</Trigger>
</Style.Triggers>
</Style>
然後我試圖把它打印出來帆布爲位圖:
public BitmapSource BuildImage(Tree tree)
{
canvas = tree.Canvas;
PrepareTree(canvas);
Size size = GetSize();
canvas.Measure(size);
canvas.Arrange(new Rect(size));
RenderTargetBitmap image = new RenderTargetBitmap(
(int)size.Width,
(int)size.Height,
96,
96,
PixelFormats.Pbgra32);
image.Render(canvas);
UnprepareTree(canvas);
return image;
}
private void UnprepareTree(Canvas canvas)
{
canvas.DottedEnabled = true;
foreach (var element in canvas.Children.OfType<IPrintable>())
{
element.IsBeingPrinted = false;
}
}
private void PrepareTree(Canvas canvas)
{
canvas.Focus();
canvas.DottedEnabled = false;
foreach (var element in canvas.Children.OfType<IPrintable>())
{
element.IsBeingPrinted = true;
}
}
的圖像看起來如此:
畫布沒有點(樣式做了它的工作),但TextBox的BorderThickness在圖像上保持爲1。 PrepareTree()
函數中的斷點顯示TextBox BorderThickness屬性設置爲零(也就是說,該樣式也可以)。 如何獲取圖像上的「新」版本的TextBoxes?
謝謝,這也爲我做了詭計!我將畫布元素繪製到BitmapRenderTarget中,而不在應用程序中顯示它們,這解決了我遇到的問題(位圖顯示爲空白)。 –