【发布时间】:2011-01-14 16:14:14
【问题描述】:
我正在绑定一个具有浮点类型属性的文本框。一切正常,我更改了 TextBox 中的值,它在属性中得到更新。当我将 TextBox 设为空白时会出现问题,我的属性没有得到更新,它仍然具有旧值。现在我需要在绑定中使用转换器来使用默认值更新属性,以防 TextBox 中出现空白值。我想知道为什么会出现这种行为?有没有其他解决办法?
【问题讨论】:
标签: .net wpf data-binding properties string
我正在绑定一个具有浮点类型属性的文本框。一切正常,我更改了 TextBox 中的值,它在属性中得到更新。当我将 TextBox 设为空白时会出现问题,我的属性没有得到更新,它仍然具有旧值。现在我需要在绑定中使用转换器来使用默认值更新属性,以防 TextBox 中出现空白值。我想知道为什么会出现这种行为?有没有其他解决办法?
【问题讨论】:
标签: .net wpf data-binding properties string
您的属性未更新,因为无法将空字符串转换为浮点数。有两种方法可以解决这个问题。
第一种方法是添加一个类型为字符串的属性,将TextBox与它绑定并实现浮动属性的更改。像这样:
public partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Window1()
{
InitializeComponent();
// don't use this as DataContext,
// it's just an example
DataContext = this;
}
private float _FloatProperty;
public float FloatProperty
{
get { return _FloatProperty; }
set
{
_FloatProperty = value;
OnPropertyCahnged("FloatProperty");
}
}
private string _StringProperty;
public string StringProperty
{
get { return _StringProperty; }
set
{
_StringProperty = value;
float newFloatValue;
// I think you want 0 when TextBox is empty, right?
FloatProperty = float.TryParse(_StringProperty, out newFloatValue) ? newFloatValue : 0;
OnPropertyCahnged("StringProperty");
}
}
protected void OnPropertyCahnged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("StringProperty"));
}
}
}
第二种方法是使用转换器:
namespace WpfApplication3
{
public partial class Window1 : Window, INotifyPropertyChanged
{
public static readonly IValueConverter TextBoxConverter = new FloatConverter();
/* code from previous example without StringProperty */
}
public class FloatConverter : 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)
{
float f;
if (value is string && float.TryParse(value as string, out f))
{
return f;
}
return 0f;
}
}
}
XAML:
<Window x:Class="WpfApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfApplication3="clr-namespace:WpfApplication3">
<Grid>
<TextBox Text="{Binding FloatProperty, Converter={x:Static WpfApplication3:Window1.TextBoxConverter}}" />
</Grid>
</Window>
我更喜欢MVVM pattern 的第一种方式。
【讨论】:
只需像这样更改绑定
<TextBlock Text={Binding Path=Name, TargetNullValue='',UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}/>
【讨论】:
我认为问题在于绑定系统与空文本框匹配的内容。对你来说可能为零,但对其他人来说可能是 Single.NegativeInfinity。
【讨论】: