2010-11-06 54 views
2

有人可以將此XAML重寫爲C#代碼嗎?將DataGrid-GroupStyle XAML重寫爲C#代碼

<DataGrid.GroupStyle> 
       <GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}"> 
        <GroupStyle.Panel> 
         <ItemsPanelTemplate> 
          <DataGridRowsPresenter/> 
         </ItemsPanelTemplate> 
        </GroupStyle.Panel> 
       </GroupStyle> 
</DataGrid.GroupStyle> 

我試過,但沒有奏效:

// Setup Grouping 
      GroupStyle groupStyle = new GroupStyle(); 
      groupStyle.ContainerStyle.Resources.FindName("GroupHeaderStyle"); 
      groupStyle.Panel = new DataGridRowsPresenter(); 

不能老是讓最後一行的工作...

UPDATE:

// Setup Grouping 
      GroupStyle groupStyle = new GroupStyle(); 
      groupStyle.ContainerStyle.Resources.FindName("GroupHeaderStyle"); 
      groupStyle.Panel = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(DataGridRowsPresenter))); 
+0

看到你,而我回答,你得到了它的工作更新你的問題? – 2010-11-06 11:32:28

回答

1

這應該這樣做:)

FrameworkElementFactory datagridRowsPresenter = new FrameworkElementFactory(typeof(DataGridRowsPresenter)); 
ItemsPanelTemplate itemsPanelTemplate = new ItemsPanelTemplate(); 
itemsPanelTemplate.VisualTree = datagridRowsPresenter; 
GroupStyle groupStyle = new GroupStyle(); 
groupStyle.Panel = itemsPanelTemplate; 
dataGrid.GroupStyle.Add(groupStyle); 

Uri resourceLocater = new Uri("/YourAssemblyName;component/SubDirectory/YourFile.xaml", System.UriKind.Relative); 
ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater); 
groupStyle.ContainerStyle = resourceDictionary["GroupHeaderStyle"] as Style; 
+0

你的代碼很好,但我的資源「GroupHeaderStyle」是在另一個XAML文件中定義的。你給我的代碼是一個.cs自定義控制文件。你將如何訪問資源......好吧我提出一個額外的問題,這更好... – Elisabeth 2010-11-06 11:39:44

+0

更新我的答案,類似於這個取決於程序集和目錄 – 2010-11-06 11:48:27

0

這個環節必須有幫助:http://www.netframeworkdev.com/windows-presentation-foundation-wpf/setting-an-itemscontrolpanels-content-from-code-86898.shtml

順便說一句,也許你想

groupStyle.ContainerStyle = Resources.FindName("GroupHeaderStyle"); 

,而不是

groupStyle.ContainerStyle.Resources.FindName("GroupHeaderStyle"); 

編輯:
,以獲得正確的容器,你需要從資源獲取。這些是Window資源或應用程序範圍內的資源。我猜Application.Current.Resources.FindName("GroupHeaderStyle");應該找到正確的資源,除非你正在做一些特別的事情。

+0

啊是張貼舊代碼... – Elisabeth 2010-11-06 11:09:08

+0

用新代碼更新我的問題:我如何創建一個ContainerStyle,因爲它的NULL?有趣我可以創建一個Style並將其分配給ContainerStyle我認爲它只需要ContainerSTyle實例... – Elisabeth 2010-11-06 11:19:42

+0

@Lisa:也更新了我的答案。 – Vlad 2010-11-06 11:26:21