IsMaskcompleted有时为null,为什么?

问题描述

我正在处理新的WPF表单。我正在使用Extended.Wpf.Toolkit的MaskedTextBox。我在MultiBinding表达式中使用IsMaskCompleted属性。这是XAML:

<Border Grid.Row="1" 
        Grid.Column="1">
    <Border.BorderThickness>
        <MultiBinding Converter="{StaticResource multiBoolToThicknessConverter}">
            <Binding ElementName="TargetMaskedTextBox,Path=IsMaskCompleted" />
            <Binding Path="IsTargetCompleted" />
        </MultiBinding>
    </Border.BorderThickness>
    <tk:MaskedTextBox x:Name="TargetMaskedTextBox"
                      Style="{StaticResource LeftAlignMaskedTextBoxStyle}"
                      Value="{Binding Target}"
                      IsEnabled="{Binding IsTargetEnabled}"
                      ValueDataType="{x:Type System:Single}"
                      Mask="\0.0##" />
</Border>

这是我的IMultiValueConverter中的Convert方法:

public object Convert(object[] values,Type targetType,object parameter,CultureInfo culture)
{
    try
    {
        bool? boolOneNullable = values[0] as bool?;
        bool? boolTwoNullable = values[1] as bool?;

        bool boolOne = true;
        bool boolTwo = true;

        if (!boolOneNullable.HasValue)
        {
            boolOne = false;
        }
        else
        {
            boolOne = boolOneNullable.Value;
        }

        if (!boolTwoNullable.HasValue)
        {
            boolTwo = false;
        }
        else
        {
            boolTwo = boolTwoNullable.Value;
        }

        var combinedBools =  boolOne && boolTwo;

        if (combinedBools)
        {
            return new Thickness(0);
        }
        else
        {
            return new Thickness(1);
        }

    }
    catch (Exception)
    {
        return null;
    }
}

我不了解的是,当在填充了MaskedTextBox控件的数据网格中选择一行时,即使其中包含有效数据,IsMaskCompleted也通常为null。为什么呢?

解决方法

您不能假定属性在第一次调用Convert方法时已被初始化。此后不久将使用实际值再次调用它。

您应该检查是否提供了值并且没有简单返回:

public object Convert(object[] values,Type targetType,object parameter,CultureInfo culture)
{
    if (values == null || values.Length < 2 || (values[0] == null && values[1] == null))
        return;
    ...

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...