WPF 输入为空时 控件提示未能转换为值

目录

    问题描述:TextBox绑定了值,但当没有输入的时候,显示未能转换值""

    解决方案:给绑定增加converter,

    <TextBox Text="{Binding Count, Converter={StaticResource countConverter}}" />
    

    要这样绑定先要写一个converter
    C#代码:

    using System.Windows.Data;
    
    
    public class CountConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (string.IsNullOrWhiteSpace(value.ToString()))
            {
                return 0;
            }
            return value;
        }
    }
    
    

    要使用StaticResource方式要在xaml中增加资源 ,并且引用空间(这步略过)

    <converter:CountConverter x:Key="countConverter" />
    
    
    posted @ 2020-09-22 13:25  养鼠的猫  阅读(1297)  评论(0编辑  收藏  举报