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

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值,对非法数字进行丢弃。注意这两行代码的区别 } } }