Tôi đang cố gắng ràng buộc TextBox
đến double
thuộc tính của một số đối tượng với UpdateSourceTrigger=PropertyChanged
. Mục tiêu là ngay lập tức trong khi chỉnh sửa xác thực giá trị đã nhập để ở trong phạm vi cho phép (và hiển thị lỗi nếu không). Tôi muốn triển khai xác thực ở cấp Mô hình, tức là thông qua IDataErrorInfo
.Ràng buộc với trường đôi có xác nhận
Tất cả các công trình tuyệt vời khi tôi liên kết với thuộc tính int, nhưng nếu thuộc tính tăng gấp đôi thì hành vi chỉnh sửa bực bội xuất hiện: sau khi xóa chữ số quan trọng cuối cùng trong phần phân số - dấu tách thập phân sẽ tự động bị xóa (với tất cả các số phân số có thể phân số) . Ví dụ: sau khi xóa chữ số '3' khỏi số '12 .03 ', văn bản được thay đổi thành' 12 'thay vì '12 .0'.
Xin vui lòng, trợ giúp.
Đây là đoạn mã mẫu:
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));
}
}
}
Tôi tưởng tượng điều này là để làm với định dạng - vì 12 là tương đương với 12,00, bạn đã thử sử dụng StringFormat trên ràng buộc? – Charleh
Có, tôi đã thử, nhưng không thích cách chỉnh sửa hoạt động với nó. StringFormat là tốt cho trình bày, nhưng trong quá trình chỉnh sửa, tôi muốn tránh nó. – arudoy