【问题标题】:Rewrite DataGrid-GroupStyle XAML into C# code将 DataGrid-GroupStyle XAML 重写为 C# 代码
【发布时间】:2010-11-06 10:54:40
【问题描述】:

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

【问题讨论】:

  • 看到你在我回答的时候更新了你的问题,你成功了吗?

标签: c# wpf xaml datagrid groupstyle


【解决方案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;

【讨论】:

  • 您的代码很好,但我的资源“GroupHeaderStyle”是在另一个 XAML 文件中定义的。您给我的代码位于 .cs 自定义控制文件中。您将如何访问资源...好吧,我提出一个额外的问题,那就更好了...
  • 更新了我的答案,与此类似,具体取决于程序集和目录
【解决方案2】:

此链接一定有帮助: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"); 应该能找到正确的资源,除非你正在做一些特别的事情。

【讨论】:

  • 用新代码更新了我的问题:如何创建 ContainerStyle 因为它的 NULL ?有趣的是我可以创建一个 Style 并将其分配给 ContainerStyle 我认为它只需要 ContainerSTyle 实例......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多