【发布时间】:2012-02-21 10:21:23
【问题描述】:
无法通过 TextBox 绑定到 Int32 分配空值?。
如果 TextBox 为空,则不调用 Int32Null Set。
TexBox 周围有一个红色边框,表示验证异常。
这只是作为 Int32 没有意义吗?可以为空。如果用户从 TextBox 中删除整数值,我希望调用 Set,因此将属性分配为 null。
当它启动时 int32Null = null 并且 TextBox 不是红色的。
如果 TextBox 为空,我尝试实现验证并设置验证 = 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; }
}
}
Set 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;
}
}
【问题讨论】:
标签: c# .net wpf xaml data-binding