Estoy intentando vincular TextBox
a double
propiedad de algún objeto con UpdateSourceTrigger=PropertyChanged
. El objetivo es inmediatamente durante la edición, validar que el valor ingresado esté dentro del rango permitido (y mostrar un error si no es así). Deseo implementar la validación en el nivel del modelo, es decir, a través del IDataErrorInfo
.Enlace al campo doble con validación
Todo funciona muy bien cuando enlace a la propiedad int, pero si la propiedad es doble, aparece un comportamiento de edición frustrante: después de borrar el último dígito significativo en fracción de número, el separador decimal se borra automáticamente (con todos los ceros fraccionarios posibles) . Por ejemplo, después de borrar el dígito '3' del número '12 .03 ', el texto cambia a' 12 'en lugar de '12 .0'.
Por favor, ayuda.
Aquí es el código de ejemplo:
MainWindow.xaml:
<Window x:Class="BindWithValidation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="80" Width="200" WindowStartupLocation="CenterOwner">
<StackPanel>
<TextBox Width="100" Margin="10" Text="{Binding DoubleField, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</StackPanel>
</Window>
MainWindow.xaml.cs:
namespace BindWithValidation
{
public partial class MainWindow : Window
{
private UISimpleData _uiData = new UISimpleData();
public MainWindow()
{
InitializeComponent();
DataContext = _uiData;
}
}
}
UISimpleData.cs:
namespace BindWithValidation
{
public class UISimpleData : INotifyPropertyChanged, IDataErrorInfo
{
private double _doubleField = 12.03;
public double DoubleField
{
get
{
return _doubleField;
}
set
{
if (_doubleField == value)
return;
_doubleField = value;
RaisePropertyChanged("DoubleField");
}
}
public string this[string propertyName]
{
get
{
string validationResult = null;
switch (propertyName)
{
case "DoubleField":
{
if (DoubleField < 2 || DoubleField > 5)
validationResult = "DoubleField is out of range";
break;
}
default:
throw new ApplicationException("Unknown Property being validated on UIData");
}
return validationResult;
}
}
public string Error { get { return "not implemented"; } }
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
Me imagino que esto tiene que ver con el formateo - ya que 12 es equivalente a 12.00, ¿ha intentado utilizar StringFormat en el enlace? – Charleh
Sí, lo he intentado, pero no me gusta cómo funciona la edición. StringFormat es bueno para presentar, pero durante la edición me gustaría evitarlo. – arudoy