Your property is not updated because it is not possible to convert an empty string to a float. There are two ways to solve this problem.
The first way is to add a property whose type is a string, bind a TextBox to it, and implement a change to the float property. Like this:
public partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Window1()
{
InitializeComponent();
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;
FloatProperty = float.TryParse(_StringProperty, out newFloatValue) ? newFloatValue : 0;
OnPropertyCahnged("StringProperty");
}
}
protected void OnPropertyCahnged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("StringProperty"));
}
}
}
The second way is to use the converter:
namespace WpfApplication3
{
public partial class Window1 : Window, INotifyPropertyChanged
{
public static readonly IValueConverter TextBoxConverter = new FloatConverter();
}
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>
There is an article about converters
I prefer the first way with the MVVM pattern .
source
share