2015-04-28 26 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