2015-04-28 25 views
0

目标样式并不适用于无头WPF控件

我有一些嵌套ItemsControls WPF窗口。我需要将这些项目提取到位图中,但实际上没有显示窗口。到目前为止,我已经通过渲染可视化树而不显示实际窗口的一些障碍。

问题

我的问题是,输出不具有适用于它的样式。

事情我已经试过

  • 如果我第一个显示窗口,然后得到的位图,然后关闭窗口一切正常(样式都适用)。虽然,我不认为这个“黑客”是可以接受的,但更多的是一种排除故障的方式。
  • 结束语在ViewBoxContentPresenter,并做了.Measure().Arrange()但这并没有帮助

我引用thesequestions让我更接近把事情做对,但可惜的风格依然不应用。我认为我错过了强制应用样式的某种步骤。任何帮助,将不胜感激。通知你,我在2012年VS

道歉使用.NET 4中,如果这个代码位不太匹配。正如上面提到的那样,有一堆嵌套的ItemsControls,为了简洁起见,我试图将所有内容细化,以便更容易遵循。

设置控制

ucAncillary ancillaryControl = new ucAncillary(AncillaryGroups); 
ancillaryControl.ApplyTemplate(); 
ancillaryControl.UpdateLayout(); 
ancillaryControl.Measure(new System.Windows.Size(Double.PositiveInfinity, Double.PositiveInfinity)); 
ancillaryControl.Arrange(new Rect(ancillaryControl.DesiredSize)); 

//AncillaryGroups is the name of the ItemsControl that I want the items from 
ancillaryControl.AncillaryGroups.generateContainers(); 

foreach (var group in AncillaryGroups) 
{ 
    var groupControl = this.AncillaryGroups.ItemContainerGenerator.ContainerFromItem(group) as ContentPresenter; 
    groupControl.ApplyTemplate(); 

    RenderTargetBitmap rtb = new RenderTargetBitmap((int)groupControl.DesiredSize.Width, (int)groupControl.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32); 
    rtb.Render(groupControl); 

    MemoryStream stream = new MemoryStream(); 
    BitmapEncoder encoder = new PngBitmapEncoder(); 
    encoder.Frames.Add(BitmapFrame.Create(rtb)); 
    encoder.Save(stream); 

    type.RenderedBitmap = new Bitmap(stream); 
} 

上述

public static void generateContainers(this ItemsControl c) 
{ 
    IItemContainerGenerator generator = c.ItemContainerGenerator; 
    GeneratorPosition position = generator.GeneratorPositionFromIndex(0); 
    using (generator.StartAt(position, GeneratorDirection.Forward, true)) 
    { 
     foreach (object o in c.Items) 
     { 
      DependencyObject dp = generator.GenerateNext(); 
      generator.PrepareItemContainer(dp); 
     } 
    } 
} 

回答

1

提到的GenerateContainers功能,您可以自己去衡量和渲染之前再安排新的控件:

var groupControl = ...; 
groupControl.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); 
groupControl.Arrange(new Rect(groupControl.DesiredSize)); 

这是通过记忆,我会仔细检查自己,如果需要更新。

+0

就是这样!我可以发誓,我有一点,但我不能有。非常感谢你! – jmgardn2