wpf datagrid 设置自动新增行后 避免行内没有内容也会新增行处理

前台

csharp 复制代码
<DataGrid
    AutoGenerateColumns="False"
    Background="White"
    CanUserAddRows="True"
    Grid.Row="1"
    RowEditEnding="DataGrid_OnRowEditEnding"
    RowHeight="60"
    SelectionUnit="CellOrRowHeader"
    x:Name="DataGrid">


<!-- Mode=TwoWay, UpdateSourceTrigger=PropertyChanged  这两个设置很重要,没有的话无法实现双向绑定-->
    <DataGrid.Columns>
        <DataGridTextColumn
            Binding="{Binding ZhuJieNeiRong, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
            Header="注解内容"
            Width="*">
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="TextBlock">
                    <Setter Property="VerticalAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.ElementStyle>

<!-- -->
<!-- 这里的功能是 如果设定了行高,加上这个样式 编辑表格时 内容是一直垂直居中-->
            <DataGridTextColumn.EditingElementStyle>
                <Style TargetType="TextBox">
                    <Setter Property="VerticalContentAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.EditingElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>


</DataGrid>

后台

csharp 复制代码
private void DataGrid_OnRowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {
        var newItem = e.Row.Item as Zjwz;
        Console.WriteLine("1111:"+ _gridZhuJieList);
        // 检查新行是否为空
        if (newItem != null)
        {
            if (!string.IsNullOrWhiteSpace(newItem.ZhuJieNeiRong))
            {
                
            }
            else
            {
                // 如果新行为空,取消新增
                e.Cancel = true;

                // 可选:可以选择清空新行的内容,或者提示用户
                // MessageBox.Show("新行不能为空!");
            }
        }
    }


}
相关推荐
龙侠九重天1 小时前
C# 机器学习数据处理
开发语言·人工智能·机器学习·ai·c#
筱璦14 小时前
期货软件开发 - C# 调用 HQChart 指标计算 C++ 动态库
c++·microsoft·c#
武藤一雄15 小时前
C# 异常(Exception)处理避坑指南
windows·microsoft·c#·.net·.netcore·鲁棒性
武藤一雄18 小时前
WPF中ViewModel之间的5种通讯方式
开发语言·前端·microsoft·c#·wpf
雨浓YN18 小时前
OPC UA 通讯开发笔记 - 基于Opc.Ua.Client
笔记·c#
我是唐青枫19 小时前
C#.NET TPL Dataflow 深入解析:数据流管道、背压控制与实战取舍
c#·.net
SunnyDays10111 天前
如何使用 C# 创建、修改和删除 Excel 中的 VBA 宏(无需Microsoft Excel)
c#·excel·vba宏·创建vba宏·修改vba宏·删除vba宏
唐青枫1 天前
C#.NET gRPC 深入解析:Proto 定义、流式调用与服务间通信取舍
c#·.net
水深00安东尼1 天前
C# 鼠标点击小游戏
c#
波波0071 天前
每日一题:C#中using的三种用法
开发语言·c#