WPF 基础 - Binding 对数据的转换和校验
2021-03-01 00:26
标签:bst class source obj ESS 检验 rri 数据 new Binding 中,有检验和转换关卡。 源码: 实例: 源码: 实例: WPF 基础 - Binding 对数据的转换和校验 标签:bst class source obj ESS 检验 rri 数据 new 原文地址:https://www.cnblogs.com/MichaelLoveSna/p/14442848.html1. Binding 对数据的转换和校验
1.1 数据校验
namespace System.Windows.Data
{
public class Binding : BindingBase
{
...
public Collection
拓展:
namespace System.Windows.Controls
{
public static class Validation
{
// 校验失败时触发的事件
public static readonly RoutedEvent ErrorEvent;
}
//
// 摘要:
// 表示一个验证错误,该错误可通过 System.Windows.Controls.ValidationRule 报告验证错误时由绑定引擎创建
public class ValidationError
{
public object ErrorContent { get; set; }
}
}
RangeValidationRule rvr = new RangeValidationRule();
rvr.ValidatesOnTargetUpdated = true;
bindingS.ValidationRules.Add(rvr);
bindingS.NotifyOnValidationError = true;
this.textBoxA.SetBinding(TextBox.TextProperty, bindingS);
this.textBoxA.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(this.ValidationError));
private void ValidationError(object sender, RoutedEventArgs e)
{
if (Validation.GetErrors(this.textBoxA).Count > 0)
{
MessageBox.Show(Validation.GetErrors(this.textBoxA)[0].ErrorContent.ToString();
}
}
1.2 数据转换
namespace System.Windows.Data
{
public interface IValueConverter
{
// Source To Target
object Convert(object value, Type targetType, object parameter, CultureInfo culture);
// Target To Source
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
}
}
public enum Category
{
Bomber,
Fighter
}
public class CategoryToSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Category c = (Category)value;
switch (c)
{
case Category.Bomber:
return @"llcons\Bomber.png";
case Category.Fighter:
return @"\lcoos\Fighter.png";
default:
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}