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


}
相关推荐
枯萎穿心攻击3 小时前
ECS由浅入深第三节:进阶?System 的行为与复杂交互模式
开发语言·unity·c#·游戏引擎
小码编匠4 小时前
WPF 自定义TextBox带水印控件,可设置圆角
后端·c#·.net
水果里面有苹果4 小时前
17-C#的socket通信TCP-1
开发语言·tcp/ip·c#
阿蒙Amon11 小时前
C# Linq to SQL:数据库编程的解决方案
数据库·c#·linq
iCxhust14 小时前
c# U盘映像生成工具
开发语言·单片机·c#
emplace_back15 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
阿蒙Amon16 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
深海潜水员17 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#
开开心心_Every17 小时前
便捷的Office批量转PDF工具
开发语言·人工智能·r语言·pdf·c#·音视频·symfony