我試圖綁定TextBox
到double
某些對象的屬性與UpdateSourceTrigger=PropertyChanged
。我們的目標是在編輯過程中立即使輸入的值保持在允許範圍內(如果不是,則顯示錯誤)。我想要在模型層面實現驗證,即通過IDataErrorInfo
。驗證綁定到雙字段
當我綁定到int屬性時,所有的工作都很好,但是如果屬性爲double,那麼會出現令人沮喪的編輯行爲:在擦除數字小數部分的最後一位有效數字後 - 小數點分隔符會自動擦除(所有可能的小數零) 。例如,在從數字'12.03'擦除數字'3'之後,文本被改變爲'12'而不是'12.0'。
請幫忙。
下面是示例代碼:
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));
}
}
}
我想這是用格式化 - 因爲12相當於12.00,你試過使用StringFormat綁定? – Charleh
是的,我試過了,但不喜歡編輯如何使用它。 StringFormat適合呈現,但在編輯期間,我想避免它。 – arudoy