无法为Nullable Int32分配空值?通过绑定

时间:2012-01-29 01:00:47

标签: c# .net wpf xaml data-binding

无法通过TextBox绑定到Int32?分配空值。 如果TextBox为空,则不调用Int32Null Set TexBox周围有一个红色边框,表示验证异常。

这只是Int32没有意义吗?是可以为空的。如果用户从TextBox中删除整数值,我希望调用Set,以便将属性赋值为null。

当它启动int32Null = null并且TextBox不是红色时。

如果TextBox为空,我尝试实现验证并设置validation = true。但仍未调用Set,TextBox为红色,表示验证错误。

似乎我应该能够通过绑定为空值分配空值。

    <Window x:Class="AssignNull.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
            DataContext="{Binding RelativeSource={RelativeSource self}}"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <TextBox Grid.Row="0" Grid.Column="0" Text="{Binding Path=Int32Null, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
            <TextBox Grid.Row="2" Grid.Column="0" Text="{Binding Path=StringNull, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
        </Grid>
    </Window>
    public partial class MainWindow : Window
    {
        private Int32? int32Null = null;
        private string stringNull = "stringNull";
        public MainWindow()
        {
            InitializeComponent();
        }
        public Int32? Int32Null
        {
            get { return int32Null; }
            set { int32Null = value; }
        }
        public string StringNull
        {
            get { return stringNull; }
            set { stringNull = value; }
        }
    } 

设置StringNull会被调用,传递的值不是null,而是string.empty。

由于在Int32Null上没有调用Set,我不知道传递了什么。

它还将一个string.empty传递给Int32?。不得不将空字符串转换为null。

    [ValueConversion(typeof(Int32?), typeof(String))]
    public class Int32nullConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Int32? int32null = (Int32?)value;
            return int32null.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strValue = value as string;
            if(string.IsNullOrEmpty(strValue.Trim())) return null;
            Int32 int32;
            if (Int32.TryParse(strValue, out int32))
            {
                return int32;
            }
            return DependencyProperty.UnsetValue;
        }
    }

1 个答案:

答案 0 :(得分:1)

你对type converters应如何处理这个问题做出错误的假设。因此,如果他们没有按照您的意愿行事,即将空字符串转换为null,您必须自己编写或使用Binding.Converter为您进行转换。

相关问题