当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. React系列之--props属性

    版权声明:本文为博主原创文章,未经博主允许不得转载. PS:转载请注明出处作者:TigerChain地址:http://www.jianshu.com/p/fa81cebac3ef本文出自TigerC ...

  2. 嵌入式驱动开发之---Linux ALSA音频驱动(一)

    本文的部分内容参考来自DroidPhone的博客(http://blog.csdn.net/droidphone/article/details/6271122),关于ALSA写得很不错的文章,只是少 ...

  3. EF Core 日志跟踪sql语句

    EF Core 日志跟踪sql语句 官方文档链接:https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging 1.新增自定义ILogg ...

  4. 【iOS开发-51】案例学习:动画新写法、删除子视图、视图顺序、延迟方法、button多功能使用方法及icon图标和启动页设置

    案例效果: (1)导入所需的素材,然后用storyboard把上半截位置和大小相对固定的东西布局起来.当然,这些控件也要定义成对应地IBOutlet和IBAction方便兴许使用它们. 注意:本案例在 ...

  5. Ansible@一个高效的配置管理工具--Ansible configure management--翻译(十一)

    无书面授权,请勿转载 第五章 自己定义模块 Using a module Now that we have written our very first module for Ansible, we ...

  6. AWS:2.根设备类型、EC2生命周期状态、User Data

    主要内容 1.根设备类型 linux: /dev/sda1 windows: 系统盘 2.实例生命周期 生命周期状态:停止.终止.重启 3.用户数据(UserData) 实例在初始化,运行之前给定的用 ...

  7. iOS UIWebview添加请求头的两种方式

    1.在UIWebviewDelegate的方法中拦截request,设置request的请求头,废话不多说看代码: - (BOOL)webView:(UIWebView *)webView shoul ...

  8. react-navigation遇到的坑

    关于goBack返回指定页面 react-navigation是提供了goBack()到指定页面的方法的,那就是在goBack()中添加一个参数,但当你使用goBack('Main')的时候,你会发现 ...

  9. git版本控制-- Windows+Git+TortoiseGit+COPSSH安装图文教程

    Windows+Git+TortoiseGit+COPSSH 安装图文教程 教程网址: http://www.liaoxuefeng.com/wiki/0013739516305929606dd183 ...

  10. 查看物料凭证MB03 /MIGO A04-显示,R02-物料凭证

    当货物移动操作后,可以使用事物码MB03.MIGO查询最近一次生成的物料凭证, 如果未知凭证号,Table:MKPF / AUFM/EKBE MKPF 抬头:物料凭证 KEY: MBLNR 物料凭证编 ...