You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Grid添加行?修改代码实现图片标红行添加效果

如何向WPF DataGrid添加行并实现标红行样式效果

嘿,我来帮你搞定这两个问题——给DataGrid添加行,还有实现你想要的标红行效果。咱们一步一步来:

1. 先搞定添加行的基础:数据绑定

WPF的DataGrid最推荐用数据绑定+ObservableCollection的方式来管理行数据,这样添加/删除行时界面会自动更新。首先咱们要定义对应的数据模型:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class CleanRoomData : INotifyPropertyChanged
{
    private int _id;
    public int ID
    {
        get => _id;
        set { _id = value; OnPropertyChanged(); }
    }

    private string _serviceDays1to2;
    public string ServiceDays1to2
    {
        get => _serviceDays1to2;
        set { _serviceDays1to2 = value; OnPropertyChanged(); }
    }

    private string _serviceDays3to5;
    public string ServiceDays3to5
    {
        get => _serviceDays3to5;
        set { _serviceDays3to5 = value; OnPropertyChanged(); }
    }

    private string _serviceDays6to8;
    public string ServiceDays6to8
    {
        get => _serviceDays6to8;
        set { _serviceDays6to8 = value; OnPropertyChanged(); }
    }

    // 新增:用来标记是否需要标红的属性
    private bool _isHighlighted;
    public bool IsHighlighted
    {
        get => _isHighlighted;
        set { _isHighlighted = value; OnPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

然后在你的窗口后台代码里,初始化这个集合并绑定到DataGrid:

using System.Collections.ObjectModel;

public partial class YourWindowClassName : Window
{
    public ObservableCollection<CleanRoomData> CleanRoomList { get; set; }

    public YourWindowClassName()
    {
        InitializeComponent();
        CleanRoomList = new ObservableCollection<CleanRoomData>();
        dataOfCleanRooms.ItemsSource = CleanRoomList;

        // 可以先加一行测试数据看看效果
        CleanRoomList.Add(new CleanRoomData
        {
            ID = 1,
            ServiceDays1to2 = "Pon, Śro",
            ServiceDays3to5 = "Wt, Czw",
            ServiceDays6to8 = "Pt",
            IsHighlighted = false
        });
    }

    // 按钮点击事件:添加新行
    private void CheckDateFromTo_Click(object sender, RoutedEventArgs e)
    {
        // 这里可以根据dateFrom和dateTo的值生成对应的数据
        var newRow = new CleanRoomData
        {
            ID = CleanRoomList.Count + 1,
            ServiceDays1to2 = "自定义内容", // 替换成你从日期选择器获取的逻辑
            ServiceDays3to5 = "自定义内容",
            ServiceDays6to8 = "自定义内容",
            IsHighlighted = true // 设置为true,让这行标红
        };
        CleanRoomList.Add(newRow);
    }

    // 保留你原来的DatePicker事件
    private void DatePicker_DataFrom(object sender, SelectionChangedEventArgs e)
    {
        // 你的原有逻辑
    }

    private void DatePiker_DataTo(object sender, SelectionChangedEventArgs e)
    {
        // 你的原有逻辑
    }
}

2. 实现标红行的样式

接下来修改DataGrid的XAML,添加RowStyle和DataTrigger,根据IsHighlighted属性来触发标红效果:

<DataGrid x:Name="dataOfCleanRooms" CanUserSortColumns="False" Margin="0,157,-0.4,0.4" 
          AutoGenerateColumns="False" CanUserResizeRows="False" CanUserResizeColumns="False" 
          IsReadOnly="True">
    <!-- 你的原有列定义保持不变 -->
    <DataGrid.Columns>
        <DataGridTextColumn Header="Data" Binding="{Binding ID}"></DataGridTextColumn>
        <DataGridTextColumn Header="Piętra 1-2" Binding="{Binding ServiceDays1to2}"></DataGridTextColumn>
        <DataGridTextColumn Header="Serwis duży"></DataGridTextColumn>
        <DataGridTextColumn Header="Serwis mały"></DataGridTextColumn>
        <DataGridTextColumn Header="Piętra 3-5" Binding="{Binding ServiceDays3to5}"></DataGridTextColumn>
        <DataGridTextColumn Header="Serwis duży"></DataGridTextColumn>
        <DataGridTextColumn Header="Serwis mały"></DataGridTextColumn>
        <DataGridTextColumn Header="Piętra 6-8" Binding="{Binding ServiceDays6to8}"></DataGridTextColumn>
    </DataGrid.Columns>

    <!-- 添加行样式:根据IsHighlighted标红 -->
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <!-- 默认样式 -->
            <Setter Property="Foreground" Value="Black"/>
            <Setter Property="Background" Value="White"/>

            <!-- 触发标红的条件 -->
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsHighlighted}" Value="True">
                    <!-- 可以选择标红文字或者背景,按需调整 -->
                    <Setter Property="Foreground" Value="Red"/>
                    <!-- 如果需要背景高亮,取消下面的注释 -->
                    <!-- <Setter Property="Background" Value="#FFF2DCDA"/> -->
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

完整修改后的XAML

把你原来的Grid替换成下面这段,整合了所有修改:

<Grid x:Name="tableDateFromTo">
    <DatePicker x:Name="dateFrom" SelectedDateFormat="Short" SelectedDateChanged="DatePicker_DataFrom" 
                HorizontalAlignment="Left" Margin="180,57,0,0" VerticalAlignment="Top" Height="28" FontSize="14" Width="100"/>
    <DatePicker x:Name="dateTo" SelectedDateFormat="Short" SelectedDateChanged="DatePiker_DataTo" 
                HorizontalAlignment="Left" Margin="311,57,0,0" VerticalAlignment="Top" Height="28" FontSize="14" Width="100"/>
    <Label x:Name="label" Content="Wybierz zakres dat: Od" HorizontalAlignment="Left" Margin="10,56,0,0" 
           VerticalAlignment="Top" FontSize="16"/>
    <Label x:Name="labelDateTo" Content="Do" HorizontalAlignment="Left" Margin="280,56,0,482" FontSize="16"/>
    <Button x:Name="checkDateFromTo" Content="Wybierz" HorizontalAlignment="Left" Margin="416,57,0,0" 
            VerticalAlignment="Top" FontSize="16" Height="28" Width="75" Click="CheckDateFromTo_Click"/>
    
    <DataGrid x:Name="dataOfCleanRooms" CanUserSortColumns="False" Margin="0,157,-0.4,0.4" 
              AutoGenerateColumns="False" CanUserResizeRows="False" CanUserResizeColumns="False" 
              IsReadOnly="True">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Data" Binding="{Binding ID}"></DataGridTextColumn>
            <DataGridTextColumn Header="Piętra 1-2" Binding="{Binding ServiceDays1to2}"></DataGridTextColumn>
            <DataGridTextColumn Header="Serwis duży"></DataGridTextColumn>
            <DataGridTextColumn Header="Serwis mały"></DataGridTextColumn>
            <DataGridTextColumn Header="Piętra 3-5" Binding="{Binding ServiceDays3to5}"></DataGridTextColumn>
            <DataGridTextColumn Header="Serwis duży"></DataGridTextColumn>
            <DataGridTextColumn Header="Serwis mały"></DataGridTextColumn>
            <DataGridTextColumn Header="Piętra 6-8" Binding="{Binding ServiceDays6to8}"></DataGridTextColumn>
        </DataGrid.Columns>

        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Setter Property="Foreground" Value="Black"/>
                <Setter Property="Background" Value="White"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsHighlighted}" Value="True">
                        <Setter Property="Foreground" Value="Red"/>
                        <!-- <Setter Property="Background" Value="#FFF2DCDA"/> -->
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>
</Grid>

这样一来,点击"Wybierz"按钮就会添加一行标红的新数据,而且后续你可以根据自己的逻辑调整IsHighlighted的值来控制哪些行需要标红。

内容的提问来源于stack exchange,提问作者Kamil M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:38:33