multibinding 验证数据

    public partial class MainWindow : Window
    {
        //multibinding 其实就是把 每个binding 的数据汇聚到 一个object[]的数组中
        //所以把multibinding关联到控件之前,一定要设置一个Convertor,这个    
// Convertor 从 IMultiValueConverter
        public MainWindow()
        {
            InitializeComponent();
            Binding b1 = BindgingFactory.getBinding(textbox1, "Text");
            Binding b2 = BindgingFactory.getBinding(textbox2, "Text");
            Binding b3 = BindgingFactory.getBinding(textbox3, "Text");
            Binding b4 = BindgingFactory.getBinding(textbox4, "Text");
            MultiBinding mb = new MultiBinding();
            mb.Bindings.Add(b1);
            mb.Bindings.Add(b2);
            mb.Bindings.Add(b3);
            mb.Bindings.Add(b4);
            mb.Converter = new LogonConvertor();
            mb.Mode = BindingMode.OneWay;
            mb.ValidationRules.Add(new TextValidationRule());
            //当验证结果为错误时,通知target对象,
            //多路绑定无法使用validationRule 来做验证
            /*
            mb.NotifyOnValidationError = true;
            button1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(ErrorEventHandler));
            button1.SetBinding(Button.IsEnabledProperty, mb);
            */

        }
        /*
        private void ErrorEventHandler(object sender, RoutedEventArgs args)
        {
           string errorContent =  Validation.GetErrors(button1)[0].ErrorContent.ToString();
           MessageBox.Show(errorContent);
        }
         */
    }

    class TextValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            bool? result = (bool?)value;
            if (result == true)
                return new ValidationResult(true, null);
            else
                return new ValidationResult(false, "数据不正确");
        }
    }


    class LogonConvertor : IMultiValueConverter
    {

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!values.Cast<string>().Any<string>(text => string.IsNullOrEmpty(text)) && values[0].ToString().Equals(values[1].ToString()) && values[2].ToString().Equals(values[3].ToString()))
            {
                return true;
            }
            else
                return false;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    public class BindgingFactory
    {
        public static Binding getBinding(object source , string path)
        {
            Binding b = new Binding(path);
            b.Source = source;
            return b;
        }
    }

  

posted @ 2014-07-27 02:05  jayroe  阅读(173)  评论(1)    收藏  举报