开发者

How to fire Property Set for Textboxes bound to numeric data

I just noticed that WPF textboxes bound to numeric data do not fire Property Set when non-numeric events happen such as letters/spaces typed or text cleared. This becomes a problem when I'm trying to validate that a textbox has a valid number. If the user types in 5 and presses backspace, the databound property remains 5 while the textbox appears empty! I have no way of disabling a button to stop further progress. Is there anyway to enable non-numeric notifications when bound to numeric data? Or, am I force开发者_JS百科d to use a string property/data converter? Thanks.


If you do not like the default converter you need to create your own which returns a valid value if the input is empty or unparsable.

public class IntBindingConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string input = value as string;
        if (String.IsNullOrWhiteSpace(input))
        {
            return 0;
        }
        else
        {
            int outInt;
            if (int.TryParse(input, out outInt))
            {
                return outInt;
            }
            else
            {
                return 0;
            }
        }
    }
}

Example usage:

<TextBox>
    <TextBox.Text>
        <Binding Path="Max">
            <Binding.Converter>
                <vc:IntBindingConverter/>
            </Binding.Converter>
        </Binding>
    </TextBox.Text>
</TextBox>

This may look a bit messy but normally you in fact just stop the user from proceeding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜