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


}
相关推荐
hixiong1237 小时前
C# OpenCVSharp使用 读光-票证检测矫正模型
人工智能·opencv·c#
霜绛7 小时前
C#知识补充(二)——命名空间、泛型、委托和事件
开发语言·学习·unity·c#
好望角雾眠7 小时前
第四阶段C#通讯开发-6:Socket之UDP
开发语言·笔记·学习·udp·c#
霜绛8 小时前
C#知识补充(一)——ref和out、成员属性、万物之父和装箱拆箱、抽象类和抽象方法、接口
开发语言·笔记·学习·c#
爱编程的鱼9 小时前
C# var 关键字详解:从入门到精通
开发语言·c#·solr
玩泥巴的10 小时前
解放双手!使用Roslyn生成代码让你的 HTTP 客户端开发变得如此简单
c#·.net·代码生成·roslyn
星释11 小时前
Rust 练习册 :Pig Latin与语言游戏
游戏·rust·c#
蒲公英源码12 小时前
超市进销存源码
sqlserver·c#·.net
星光一影17 小时前
PDF工具箱/合并拆分pdf/提取图片
pdf·c#
Aevget18 小时前
界面控件DevExpress WPF v25.1新版亮点:数据管理功能全新升级
.net·wpf·界面控件·devexpress·ui开发