WPF 使用MultiBinding ,TwoWay ,ValidationRule ,需要注意的事项

当wpf使用multibinding时, 其内部的validaterule的value 是其多个Binding的值, 要根据情况去验证, 还有就是在做IMultiConverter的ConvertBack时注意TargetType

如: 以下是一个Textbox通过MultiBinding绑定到后台 的字段, 以及前台的一个radiobutton, 该textbox有个validaterule。 



  < TextBox x : Name ="txtPatientWeight" TextWrapping ="Wrap" Margin ="3" MaxLength ="5" TabIndex ="6" BorderBrush ="Black" Grid.Row ="5" Grid.Column ="1" Height ="22" MinWidth ="42" Tag ="PatientWeight"
                     Visibility ="{ Binding DataContext , ElementName =window, Converter ={ StaticResource KeyToVisibilityConverter }, ConverterParameter =PatientWeight}">
                < MultiBinding   Mode ="TwoWay" Converter ="{ StaticResource WeightConverter }"    UpdateSourceTrigger ="PropertyChanged">
                    < MultiBinding.ValidationRules >
                        < McsfPAFEContainee_ValidationRules : WeightValidationRule ValidatesOnTargetUpdated ="True" ValidationStep ="ConvertedProposedValue"/>
                    </ MultiBinding.ValidationRules >
                    < Binding Path ="PatientWeight"/>
                    < Binding Path ="IsChecked" ElementName ="rdoKg"/>
                </ MultiBinding >
                < i : Interaction.Behaviors >
                    < McsfPAFEContainee_Behaviors : NumericTextBoxBehavior MinValue ="0" MaxValue ="300" />
                </ i : Interaction.Behaviors >
            </ TextBox >
////////////////////////
 <RadioButton x:Name="rdoKg" Content="kg" GroupName="WeightMeasure" d:LayoutOverrides="GridBox" MinWidth="34" Margin="5,0,0,0" Tag="PatientWeight" HorizontalAlignment="Center">
                    < RadioButton.IsChecked >
                        < Binding Path ="DataContext" Mode ="TwoWay" ElementName ="window" Converter ="{ StaticResource DefaultUnitConverter }" ConverterParameter ="kg"   UpdateSourceTrigger ="PropertyChanged"></ Binding >
                    </ RadioButton.IsChecked >
                </ RadioButton >

//////////////
   private string patientWeight = "" ; //(0010,1030) Patient Weight PatientWeight DS unit kg

        public string PatientWeight
        {
            get { return patientWeight ; }
            set
            {
                if ( value == patientWeight )
                {
                    return ;
                }

                patientWeight = value ;
                OnPropertyChanged ( "PatientWeight" );
            }
        }
  


//////////converter
  public class WeightConverter : IMultiValueConverter
    {
        public object Convert( object [] values, Type targetType, object parameter, CultureInfo culture)
        {
            if ( null == values || 2 != values.Length )
            {
                return "" ;
            }

            string unit = "" ;
            string temp = values[0].ToString();

            if ( String .IsNullOrEmpty(temp))
            {
                return "" ;
            }

            if (0 <= temp.IndexOf( "lb" ))
            {
                unit = "lb" ;
            }
            else if (0 <= temp.IndexOf( "kg" ))
            {
                unit = "kg" ;
            }
            else
            {
                return "" ;
            }

            string number = "" ;
            number = temp.Substring(0, temp.IndexOf(unit));

            //KG
            if (( bool )values[1])
            {
                measurementUnit = "kg" ;
            }
            else //LB
            {
                measurementUnit = "lb" ;
            }

            return ConvertToTargetValue(number, unit, measurementUnit);
        }

        private string measurementUnit = "" ;
      
        public object [] ConvertBack( object value, Type [] targetTypes, object parameter, CultureInfo culture)
        {
            string temp = value.ToString();

            if ( String .IsNullOrEmpty(temp))
            {
                return new object []{ DependencyProperty .UnsetValue, DependencyProperty .UnsetValue};
            }

            if ( String .IsNullOrEmpty(measurementUnit))
            {
                measurementUnit = ( PAFEContainee .MainDataContext as MainViewModel ).PRCfgVM.IsDefaultKilogram ? "kg" : "lb" ;
            }

            object [] list = new object [2];
            list[0] = value.ToString() + measurementUnit;
            list[1] = measurementUnit.Equals( "kg" ) ? "true" : "false" ;

            return list;
        }

        private string ConvertToTargetValue( string before, string beforeUnit, string afterUnit)
        {
            string result = "" ;

            if (beforeUnit.Equals(afterUnit))
            {
                return before;
            }

            switch (afterUnit)
            {
                case "lb" :
                    result = ConvertKgToPound(before).ToString();
                    break ;
                case "kg" :
                    result = ConvertPoundToKg(before).ToString();
                    break ;
                default :
                    break ;
            }

            return result;
        }

        private double ConvertPoundToKg( string pound)
        {
            double kg = 0.4536 * double .Parse(pound);

            return kg;
        }

        private double ConvertKgToPound( string kg)
        {
            double pound = 2.20 * double .Parse(kg);

            return pound;
        }

    }


///////ValidationRule
  public override ValidationResult DoValidate ( object value , CultureInfo cultureInfo )
        {
            try
            {

                //string field = value.ToString().Trim();
                string field = ( value as object [])[0]. ToString ();
                string pattern = @"^([1-9]|[1-9][0-9]|[1-5][0-9][0-9]|600)((kg)|(lb))$" ;

                Regex reg = new Regex ( pattern , RegexOptions . IgnoreCase );

                if ( field . Length <= 0 || false == reg . IsMatch ( field ))
                {
                    return new ValidationResult ( false , "Please input a number, for example '60'" );
                }
                else
                {
                    return ValidationResult . ValidResult ;
                }
            }
            catch
            {
                return new ValidationResult ( false , "Patient weight convert failed." );
            }

        }

你可能感兴趣的:(WPF)