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 @ 2019-04-30 12:10  向往蓝天的菜鸟  阅读(699)  评论(0编辑  收藏  举报