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


}
相关推荐
军训猫猫头4 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
不爱写代码的玉子5 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
明耀8 小时前
WPF DataGrid 默认显示行号
wpf
开开心心就好8 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法
一名用户10 小时前
unity实现自定义粒子系统
c#·unity3d·游戏开发
lph197212 小时前
wpf的converter
wpf
fyifei055812 小时前
WPF学习PropertyChanged
wpf
钢铁男儿12 小时前
C# 类和继承(扩展方法)
java·servlet·c#
爱炸薯条的小朋友12 小时前
C#由于获取WPF窗口名称造成的异常报错问题
windows·c#·wpf
baivfhpwxf202313 小时前
wpf ListBox 去除item 单击样式
wpf