WPF学习笔记(8):DataGrid单元格数字为空时避免验证问题的解决

原文: WPF学习笔记(8):DataGrid单元格数字为空时避免验证问题的解决

如下图,在凭证编辑窗体中,有的单元格不需要数字,但如果录入数字后再删除,会触发数字验证,单元格显示红色框线,导致不能执行其他操作。

Xaml代码如下:

<DataGridTextColumn Header="借方金额" Binding="{Binding Path=FDebit, StringFormat='#,##0.00;-#,##0.00;#'}" Width="200" ElementStyle="{StaticResource dgCellRigth}"/>

解决思路是用转换器Converter代替StringFormat:

Xmal主要代码:

<Window.Resources>
        <local:NumConver x:Key="numConverter"/>
</Window.Resources>
<DataGridTextColumn Header="借方金额" Binding="{Binding Path=FDebit, Converter={StaticResource numConverter}}" Width="200" ElementStyle="{StaticResource dgCellRigth}"/>

C#主要代码:

public class NumConver : IValueConverter
    {
        //当值从绑定源传播给绑定目标时,调用方法Convert
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strNum = value.ToString();
            if (string.IsNullOrEmpty(strNum)) return null;
            decimal decNum = (decimal)value;
            return decNum.ToString("#,##0.00;-#,##0.00;#");
        }

        //当值从绑定目标传播给绑定源时,调用此方法ConvertBack
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strNum = value.ToString();
            if (string.IsNullOrEmpty(strNum)) return null;
            decimal decNum;
            if (decimal.TryParse(strNum, out decNum))
            {
                return decNum;
            }
            else
            {
                return DependencyProperty.UnsetValue;  //未设定值,对非法数字进行数字验证,单元格以红色框线提示,等待修改
                //return null;  //null值,对非法数字进行丢弃。注意这两行代码的区别
            }
        }
    }

 

posted on 2019-04-30 12:42 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/10795370.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值