2

有人可以将此 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();

无法让最后一行工作...

更新:

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

2 回答 2

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;
于 2010-11-06T11:29:24.697 回答
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");

编辑:
为了使容器正确,您需要从资源中获取它。这些要么是窗口资源,要么是应用程序范围的资源。我想Application.Current.Resources.FindName("GroupHeaderStyle");应该找到正确的资源,除非你正在做一些特别的事情。

于 2010-11-06T11:03:28.930 回答