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("新行不能为空!");
            }
        }
    }


}
相关推荐
Yorlen_Zhang6 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
不绝1916 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
大鹏说大话6 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
风指引着方向7 小时前
归约操作优化:ops-math 的 Sum/Mean/Max 实现
人工智能·wpf
czhc11400756638 小时前
通信 28
c#
听麟10 小时前
HarmonyOS 6.0+ 跨端智慧政务服务平台开发实战:多端协同办理与电子证照管理落地
笔记·华为·wpf·音视频·harmonyos·政务
bugcome_com11 小时前
C# 程序结构详解:从 Hello World 开始
c#
唐梓航-求职中12 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
听麟14 小时前
HarmonyOS 6.0+ APP AR文旅导览系统开发实战:空间定位与文物交互落地
人工智能·深度学习·华为·ar·wpf·harmonyos
bugcome_com14 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#