设为首页 加入收藏

TOP

WPF学习笔记(8):DataGrid单元格数字为空时避免验证问题的解决
2019-09-17 18:33:24 】 浏览:12
Tags:WPF 学习 笔记 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值,对非法数字进行丢弃。注意这两行代码的区别 } } }

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇WPF学习笔记(7):DataGrid中数.. 下一篇位运算

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目