当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");
            }
        }
  
 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;
        }
    }
 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 使用MultiBinding ,TwoWay ,ValidationRule ,需要注意的事项的更多相关文章

  1. WPF支持OneWay,TwoWay,OneTime,Default和OneWayToSource

    原文:WPF支持OneWay,TwoWay,OneTime,Default和OneWayToSource 无论是目标属性还是源属性,只要发生了更改,TwoWay 就会更新目标属性或源属性. OneWa ...

  2. 【WPF】wpf用MultiBinding解决Converter需要动态传参的问题,以Button为例

    原文:[WPF]wpf用MultiBinding解决Converter需要动态传参的问题,以Button为例       用Binding并通过Converter转换的时候,可能偶尔会遇到传参的问题, ...

  3. 总结:WPF中MultiBinding多值绑定的方法

    原文:总结:WPF中MultiBinding多值绑定的方法 一.Xaml中绑定代码: <TextBlock  Grid.Row="5" Grid.Column="3 ...

  4. WPF Get Multibinding Expression, Update Source,

    wpf 拿到某个control的multibinding以及其中每个Binding 1. 拿到multibinding      MultiBindingExpression mbe = Bindin ...

  5. WPF 之 MultiBinding(多路 Binding)(四)

    一.前言 ​ 有时候 UI 需要显示的信息由不止一个数据来源决定,这时候就需要使用 MultiBinding ,即多路 Binding. ​ MultiBinding 与 Binding 一样均以 B ...

  6. WPF 基础 - MultiBinding

    MultiBinding 与 Binding 一样继承自 BindingBase,因此可以使用 Binding 的地方都可以使用 MultiBinding. namespace System.Wind ...

  7. WPF:自动执行"机器人"程序若干注意事项

    企业应用中,经常会遇到一些需要定时自动执行的程序来完成某些功能,比如:自动定时从第三方web service取回数据.定时对历史数据进行清理.定时向ftp上传业务数据... 这类程序,我习惯称为“机器 ...

  8. WPF关于改变ListBoxItem的颜色的注意事项以及如何找到ListBox中的ItemsPanel

    在ListBox中碰到过几个问题,现在把它写出来: 第一个就是在ListBoxItem中当我用触发器IsSelected和IsMouseOver来设置Background和Foreground的时候, ...

  9. WPF 关于拖拽打开文件的注意事项

    由于开发需求,需要开发一个类似Win图片浏览的工具 当然也涉及到了拖拽打开的需求 按照固有思路: <Grid x:Name="grid1" AllowDrop="T ...

随机推荐

  1. 根据URL发起HTTP请求,我的HTTPHelper。

     完整的demo using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...

  2. 题解 P1001 【A+B Problem】

    #include<iostream> using namespace std; #define I int a,b; #define AK cin>>a>>b; # ...

  3. Linux就该这么学--命令集合9(环境变量)

    1.alias命令用于设置命令的别名:(alias 别名=命令) alias lll ="ll" 2.unalias命令用于取消命令的别名:(unalias 别名) unalias ...

  4. FI 常用表

    FI 常用表 GL部分:FAGLFLEXT(FMGLFLEXT)   总账汇总表 GLT0        旧总帐汇总表           SKA1        总账科目主记录 (科目表)      ...

  5. ul和li 基本用法分析(这里主要想学习怎么用在导航栏中)

    常用作:导航,少量数据表格,居中 一.做导航,居中 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ...

  6. CUDA:零拷贝主机内存

    The easy way to achieve copy/compute overlap!1.Enable Host Mapping* Runtime: cudaSetDeviceFlags() wi ...

  7. 【ansible】ansible部署方式以及部署包

    最近研究ansible的使用,在使用pip安装的时候遇到很多奇怪的问题,为此采用了手动安装的方式,并编写了一键安装脚本. ansible要求机器必须安装python2.6以上版本,可以通过一下命令查看 ...

  8. log4j 2 入门实例(3)

    继承机制 所有logger都继承自root logger. 可以认为名为log4j2learn.Hello的logger继承自名为log4j2learn的logger. log4j会先查找名称是&qu ...

  9. python——进程池

    from concurrent.futures import ProcessPoolExecutor import os,random def func(name): print("%s吃了 ...

  10. web 全栈 学习 2 一个好的页面是如何炼成的

    第一章:Web页面内容的构成2.Web内容的分工一个Web页面可能的构成(视觉上看):①文字.链接.标题②交互入口(表单元素)③图片(哪些类型)④动画 Flash动画 HTML5 CSS3 动画⑤音视 ...