WPF DataGrid 组样式

2023-12-30

I have the following DataGrid in WPF with two groups.
First group is a bool flag which represents if a person is active/inactive.
The second group (or sub-group) is the ID of each person. Each person can have multiple cities, therefore the grouping for the ID, because each person is shown multiple in the DataGrid. Table persons-cities

这是 XAML:

<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataSource}">     
    <DataGrid.GroupStyle>                    
        <GroupStyle>
            <GroupStyle.ContainerStyle>
                <Style TargetType="{x:Type GroupItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type GroupItem}">
                                <Expander IsExpanded="True">
                                    <Expander.Style>
                                        <Style TargetType="{x:Type Expander}">    
                                            <Style.Triggers>
                                                <DataTrigger Binding="{Binding Name}" Value="True">
                                                    <Setter Property="Background" Value="{StaticResource ActiveBrush}"/>
                                                </DataTrigger>
                                                <DataTrigger Binding="{Binding Name}" Value="False">
                                                    <Setter Property="Background" Value="{StaticResource InactiveBrush}"/>
                                                    <Setter Property="FontStyle" Value="Italic"/>
                                                    <Setter Property="Foreground" Value="Gray"/>
                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>
                                    </Expander.Style>
                                    <Expander.Header>
                                        <StackPanel Orientation="Horizontal">
                                            <TextBlock Text="{Binding Name, Converter={StaticResource BoolToTextConverter}}" Margin="5 2 5 2"/>
                                            <TextBlock Text=":" Margin="0 2 5 2"/>
                                            <TextBlock Text="{Binding ItemCount}" Margin="0 2 0 2"/>
                                        </StackPanel>
                                    </Expander.Header>
                                        <ItemsPresenter />
                                </Expander>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </GroupStyle.ContainerStyle>
        </GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Background="LightSteelBlue">
                        <TextBlock Text="{Binding Name}" Foreground="White" Margin="5 2 5 2"/>
                    </StackPanel>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </DataGrid.GroupStyle>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel>
                        <DockPanel>
                            <Button BorderThickness="0" Content="Edit" Margin="3"
                                Command="{Binding Commands.Edit}"
                                CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                        </DockPanel>
                    </StackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True"/>
        <DataGridTextColumn Header="City" Binding="{Binding City}" IsReadOnly="True"/>                    
    </DataGrid.Columns>
</DataGrid>

一切正常! 但是,我不喜欢每个子组的蓝色行。 我想要实现的是下图中的分组样式:

对于每个子组,我希望“编辑”按钮和 ID 每人仅出现一次。 我该怎么做?是否仅在 XAML 中可行,或者我应该删除代码隐藏中的冗余内容?

Edit
这里有一些测试数据:

public class Person
{
    public Person(bool active, int id, string name, string city)
    {
        Active = active;
        ID = id;
        Name = name;
        City = city;
    }

    public bool Active { get; set; }
    public int ID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;

        var data = new ObservableCollection<Person>
        {
            new Person(true, 233, "Max", "New York"),
            new Person(true, 233, "Max", "Los Angeles"),
            new Person(true, 314, "John", "Paris"),
            new Person(true, 578, "Mary", "Vienna"),
            new Person(true, 782, "Susan", "Rome"),
            new Person(true, 782, "Susan", "Prague"),
            new Person(true, 782, "Susan", "San Francisco"),
            new Person(false, 151, "Henry", "Chicago")
        };

        DataSource = new ListCollectionView(data);
    }

    private ListCollectionView _dataSource;

    public ListCollectionView DataSource
    {
        get { return _dataSource; }
        set
        {
            _dataSource = value;
            _dataSource.GroupDescriptions.Add(new PropertyGroupDescription("Active"));
            _dataSource.GroupDescriptions.Add(new PropertyGroupDescription("ID"));
        }
    } 

I would highly建议将数据结构更改为:

public class Person {
    public bool Active { get; set; }
    public int ID { get; set; }
    public string Name { get; set; }

    public Collection Cities { get; set; }
}

否则你可以改变这个GroupStyle

<GroupStyle>
    <GroupStyle.HeaderTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Background="LightSteelBlue">
                <TextBlock Text="{Binding Name}" Foreground="White" Margin="5 2 5 2"/>
            </StackPanel>
        </DataTemplate>
    </GroupStyle.HeaderTemplate>
</GroupStyle>

To

<GroupStyle>
    <GroupStyle.ContainerStyle>
        <Style TargetType="{x:Type GroupItem}">
            <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type GroupItem}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition SharedSizeGroup="EditButtonColumn" />
                        <ColumnDefinition SharedSizeGroup="IDColumn"  />
                        <ColumnDefinition SharedSizeGroup="NameColumn" />
                        <ColumnDefinition SharedSizeGroup="PresenterColumn" Width="*" />
                    </Grid.ColumnDefinitions>
                    <Button Grid.Column="0" BorderThickness="0" Content="Edit" Margin="3"
                CommandParameter="{Binding Path=Items[0]}" />
                    <TextBlock Grid.Column="1" Text="{Binding Path=Items[0].ID}" />
                    <TextBlock Grid.Column="2" Text="{Binding Path=Items[0].Name}" />

                    <ItemsPresenter Grid.Column="3" />
                </Grid>
                </ControlTemplate>
            </Setter.Value>
            </Setter>
        </Style>
    </GroupStyle.ContainerStyle>
</GroupStyle>

更改模板以满足您的需求

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF DataGrid 组样式 的相关文章

随机推荐

  • nlme 错误

    For IGF数据来自nlme库 我收到此错误消息 lme conc 1 data IGF random age Lot Error in lme formula conc 1 data IGF random age Lot nlminb
  • jQuery Mobile:获取上一页的 ID

    我基本上需要一个自定义函数 仅在例如从主页单击 reviews 页面时使用 这是我当前使用的代码 document bind mobileinit function reviews live pagebeforeshow function
  • phpmyadmin 导出不带 DATABASE_NAME 或算法的视图

    当使用 phpmyadmin 导出 sql 转储时 它会创建如下所示的 VIEW 表 CREATE ALGORITHM UNDEFINED DEFINER root localhost SQL SECURITY DEFINER VIEW d
  • 使用 git,如何将一些未提交的更改从一个分支移动到不同文件夹中的另一个分支?

    我每天使用的同一个软件有两个不同的分支 然而 每次我检查另一个分支时 我的构建过程可能需要长达一个小时 为了解决这个问题 我刚刚在两个单独的文件夹中为每个分支检查了一次项目 我在一个分支中做了一些工作 并在提交之前意识到我位于错误的文件夹中
  • CodeIgniter 中分页的自动加载配置不起作用

    我正在尝试在我的 CI web 应用程序中实现分页 现在我将分页配置放入这样的配置文件中
  • 使用 VB.NET 执行存储过程

    这是我的程序 ALTER PROCEDURE sp addUser UserName nvarchar 50 Prenom nvarchar 50 Nom nvarchar 50 Mail nvarchar 50 Password char
  • “静态合成”是什么意思?

    我正在查看一些从 Java 字节码获得的反汇编代码 我看到一些声明如下 method static synthetic access 0 Lcom package Sample 我不明白是什么synthetic or access 0意思是
  • SQL Server 上的 Int PK 内连接与 Guid PK 内连接。执行计划

    我刚刚对 Int PK join 与 Guid PK 进行了一些测试 表结构和记录数如下所示 在这两种情况下 使用 EF4 进行 CRUD 操作的性能非常相似 众所周知 在连接中使用 Int PK 比字符串具有更好的性能 所以SQL Ser
  • 将 Service Worker 请求中的响应修改为图像

    您好 提前谢谢您 我的问题是关于使用响应网络请求服务工作者 我能够在文本或 html 的情况下处理它 但是当我尝试处理image我失败了 这是我的代码 self addEventListener fetch function event e
  • 本地主机上的 Firebase console.log?

    拿起去年春天我离开的 Firebase 项目 我不记得是怎么做的console log工作在firebase server 我有一个函数 有效 我尝试在其中编写一些调试信息 像这样 exports myfun functions https
  • 获取对象调用层次结构

    假设我有 3 个课程 class A void do A Check object call hierarchy class B void do B A a a do A class C void do C B b b do A 然后我打电
  • Facebook iOS SDK 3.2.1 - [NSError fberrorShouldNotifyUser]:无法识别的选择器发送到实例

    我刚刚将我的应用程序从 Facebook iOS SDK 3 1 升级到 3 2 1 并且我正在尝试利用 NSError 上的新 FBError 类别提供的新错误处理 代码在底部 它编译得很好 但是当发生 FB 错误时 我在运行时得到以下信
  • R从字符串中提取数字

    字符串将是 042 195 143 192 001 145 045 125 125 如何提取最后一组数字 195 192 145 125 125 Try v1 lt c 042 195 143 192 001 145 045 125 125
  • Arduino 上的 Timer1 导致串行打印无法工作

    运行下面的代码 当我从串行监视器向 Arduino 发送任何字符时 Arduino 不会打印 a 我认为timer1代码有问题 但它应该可以工作 因为这段代码是我的C课老师给我的 void setup Serial begin 115200
  • 在 Parquet 中使用嵌套数据类型有什么好处?

    在 Parquet 文件格式中使用嵌套数据类型是否会带来任何性能优势 AFAIK Parquet 文件通常是专门为查询服务创建的 例如Athena 因此创建这些值的过程也可以简单地展平这些值 从而允许更轻松的查询 更简单的模式并保留每列的列
  • 带 proguard 的 Kotlin AAR 库:如何仅保留类和方法名称?

    我正在使用 Kotlin 构建一个 android 库 aar 文件 我需要以第三方用户将看到类和方法名称的方式混淆代码 他必须能够使用它们 它们是公开的 但我需要隐藏 混淆代码本身 我尝试将此文件用于 myLibrary proguard
  • C++ 中的模块是什么?

    该术语是什么意思module在下面的句子中引用 不允许异常跨模块边界传播 这是规则 62C 编码标准 http www gotw ca publications c cs htm作者 赫伯 萨特和安德烈 亚历山德雷斯库 我现在已经阅读了这本
  • 想要 javax.swing 钩子告诉我层次结构中的哪个组件正在执行操作

    如何通过最少的代码丑化在 Swing 程序中编写一个调试挂钩 告诉我层次结构中的哪个组件实际上正在处理每个 KeyStroke 或鼠标单击 并执行在组件的操作映射中映射到它的操作 我们正在编写一个复杂的 GUI 了解这些信息将非常有用 放入
  • 如何在谷歌地图中放置两个距离500m的标记

    我们如何将两个标记放置在 500 米的距离处 假设第一个标记的 latLng 是伦敦 51 0 第二个标记放置在距离该标记 500 米的地方 我已经尝试过任何事情 但无法找到并回答它 任何想法 纬度为 60 海里 但显然经度超出了这个范围
  • WPF DataGrid 组样式

    I have the following DataGrid in WPF with two groups First group is a bool flag which represents if a person is active i