当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. 全命令行手写MapReduce并且打包运行

    主要要讲的有3个 java中的package是干啥的? 工作了好几年的都一定真正理解java里面的package关键字,这里在写MapReduce需要进行打包的时候突然发现命令行下打包运行居然不会了, ...

  2. U-Boot中关于TEXT_BASE,代码重定位,链接地址相关说明

    都知道U-BOOT分为两个阶段,第一阶段是(~/cpu/arm920t/start.S中)在FLASH上运行(一般情况 下),完成对硬件的初始化,包括看门狗,中断缓存等,并且负责把代码搬移到SDRAM ...

  3. mac下spark单机环境配置笔记

    1.安装scala 从http://www.scala-lang.org下载scala-2.11.7.tgz并解压缩 将解压缩的文件夹用mv指令移动到/usr/local/share mv [scal ...

  4. JVM内存布局及GC知识回顾

    注:本文篇幅较长,且需要有一定的java基础,建议各位看官,备好瓜子.饮料.小板凳,摆个让自己舒服的姿势,慢慢细看^_^, 文中所有素材,均来自互联网,本人只是详细梳理了一遍,形成此文. 一.JVM运 ...

  5. gulp的使用方法

    ---恢复内容开始--- 什么是gulp? Gulp.js是一个自动化构建工具,开发者可以使用它在项目开发过程中自动执行常见任务. 使用步骤: 1.全局安装gulp:    npm install - ...

  6. 成为高级Java工程师,你必须要看的技术书籍

    学习的最好途径就是看书 "学习的最好途径就是看书",这是我自己学习并且小有了一定的积累之后的第一体会.个人认为看书有两点好处: 1.能出版出来的书一定是经过反复的思考.雕琢和审核的 ...

  7. 箭头函数 this arrow function 无this

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions import w ...

  8. ajax工作原理(转)

    在写这篇文章之前,曾经写过一篇关于AJAX技术的随笔,不过涉及到的方面很窄,对AJAX技术的背景.原理.优缺点等各个方面都很少涉及null.这次写这篇文章的背景是因为公司需要对内部程序员做一个培训.项 ...

  9. 获取HDC的几种方法

    当需要在显示器上(当然包括打印机等设备上)绘图时,或者写文字的时候,需要取得设备的上下文句柄,即HDC,本文以下都称为HDC.那么,有哪些办法取得HDC呢? 1 BeginPain()和EndPain ...

  10. cdcqの省选膜你赛 题解

    题解: 第一题: 有一个很明显的性质:后面的修改不会对前面的询问做出影响,CDQ分治套上BIT即可. 第二题: 有一个类似于斜率的形式,分数规划套上树分治,码量稍大,细节稍多. 最后20W的点出题人原 ...