wpf中有validateRule类, 用于界面元素的验证, 如何后台去控制validateRule呢?

1. UI层要binding写好的ValidateRule,分为Binding和MultiBinding, 如下面分别实现了Combobox的SelectedValuePropperty的Binding
     和TextBox的TextProperty的MultiBinding。其中都有ValidationRule。
       <ComboBox x:Name="cmbAgeType" Margin="3"
                      SelectionChanged="cmbAgeType_SelectionChanged"  Background="#00000000" BorderBrush="Black" Grid.Row="4" MinWidth="0" Grid.Column="2" IsTabStop="False" SelectedIndex="0" d:LayoutOverrides="GridBox" Tag="PatientAge"
                      Visibility="{Binding DataContext, ElementName=window, Converter={StaticResource KeyToVisibilityConverter}, ConverterParameter=PatientAge}">
                <ComboBox.SelectedValue>
                    <Binding Path="PatientAge" Converter="{StaticResource AgeMeasureConverter}" Mode="TwoWay"  UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <McsfPAFEContainee_ValidationRules:EmptyValidationRule ValidatesOnTargetUpdated="True" ValidationStep="ConvertedProposedValue"/>
                        </Binding.ValidationRules>
                    </Binding>
                </ComboBox.SelectedValue>
                <!--<Binding Path="PatientAge" Converter=""  UpdateSourceTrigger="PropertyChanged"/>-->
            </ComboBox>
    
            <TextBox x:Name="txtPatientWeight" TextWrapping="Wrap" Margin="3" MaxLength="10" 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}">
                <TextBox.Text>
                    <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>
                </TextBox.Text>
                <i:Interaction.Behaviors>
                    <McsfPAFEContainee_Behaviors:NumericTextBoxBehavior MinValue="0" MaxValue="300" />
                </i:Interaction.Behaviors>
            </TextBox>
2.  后台主动触发ValidationRule的验证。 以下方法根据上面的Binding, 分别去取Binding和MultiBinding, 然后调用UpdateSource。
            private bool ValidateInput(object child, PRCfgViewModel vm, bool isUpdateSource, bool isEmergency)
        {
            BindingExpression be = null;
            MultiBindingExpression mbe = null;
            if (child is TextBox)
            {
                be = (child as TextBox).GetBindingExpression(TextBox.TextProperty);
                if (null == be)
                {
                    mbe = BindingOperations.GetMultiBindingExpression((child as TextBox), TextBox.TextProperty);
                }
            }
            else if (child is DatePicker)
            {
                be = (child as DatePicker).GetBindingExpression(DatePicker.TextProperty);
                if (null == be)
                {
                    mbe = BindingOperations.GetMultiBindingExpression((child as DatePicker), DatePicker.TextProperty);
                }
            }
            else if (child is ComboBox)
            {
                be = (child as ComboBox).GetBindingExpression(ComboBox.SelectedValueProperty);
                if (null == be)
                {
                    mbe = BindingOperations.GetMultiBindingExpression((child as ComboBox), ComboBox.SelectedValueProperty);
                }
            }
            if (null == be && null == mbe)
            {
                return false;
            }
            ValidationRule vr = null;
            if (null != be && be.ParentBinding.ValidationRules.Count > 0)
            {
                vr = be.ParentBinding.ValidationRules[0];
            }
            else if (null != mbe && mbe.ParentMultiBinding.ValidationRules.Count > 0)
            {
                vr = mbe.ParentMultiBinding.ValidationRules[0];
            }
            else
            {
                return false;
            }
            string bindingPath = "";
            if (null != be)
            {
                bindingPath = be.ParentBinding.Path.Path;
            }
            else if (null != mbe)
            {
                Binding bd = mbe.ParentMultiBinding.Bindings[0] as Binding;
                bindingPath = bd.Path.Path;
            }
            bindingPath = bindingPath.Replace(".", "_");
            if (vm.Setting.CfgInfo[bindingPath] != null)
            {
                (vr as BaseValidationRule).IsActive = !isEmergency;
                if ((vr as BaseValidationRule).IsActive)
                {
                    (vr as BaseValidationRule).IsAllowEmpty = !(vm.Setting.CfgInfo[bindingPath].IsKeyword);
                }
                else
                {
                    if (isUpdateSource)
                    {
                        if (null != be)
                        {
                            be.UpdateSource();
                        }
                        else if (null != mbe)
                        {
                            mbe.UpdateSource();
                        }
                    }
                    return true;
                }
            }
            else
            {
                (vr as BaseValidationRule).IsAllowEmpty = true;
            }
            if (isUpdateSource)
            {
                if (null != be)
                {
                    be.UpdateSource();
                }
                else if (null != mbe)
                {
                    mbe.UpdateSource();
                }
            }
            return true;
        }

WPF 后台触发 Validate UI‘s Element的更多相关文章

  1. WPF后台线程更新UI

    0.讲点废话 最近在做一个文件搜索的小软件,当文件多时,界面会出现假死的状况,于是乎想到另外开一个后台线程,更新界面上的ListView,但是却出现我下面的问题. 1.后台线程问题 2年前写过一个软件 ...

  2. 关于WPF后台触发键盘按键

    1.变向响应Tab按键 private void Grid_KeyUp(object sender, KeyEventArgs e)         {             UIElement e ...

  3. 一种WPF在后台线程更新UI界面的简便方法

    WPF框架规定只有UI线程(主线程)可以更新界面,所有其他后台线程无法直接更新界面.幸好,WPF提供的SynchronizationContext类以及C#的Lambda表达式提供了一种方便的解决方法 ...

  4. WPF 精修篇 非UI进程后台更新UI进程

    原文:WPF 精修篇 非UI进程后台更新UI进程 <Grid> <Grid.RowDefinitions> <RowDefinition Height="11* ...

  5. WPF 支持的多线程 UI 并不是线程安全的

    原文:WPF 支持的多线程 UI 并不是线程安全的 版权声明:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可.欢迎转载.使用.重新发布,但务必保留文章署名吕毅(包含链 ...

  6. WPF后台动画DoubleAnimation讲解

    WPF后台动画,使用DoubleAnimation做的. 1.移动动画 需要参数(目标点离最上边的位置,目标点离最左边的位置,元素名称) Image mImage = new Image(); Flo ...

  7. How do I duplicate a resource reference in code behind in WPF?如何在WPF后台代码中中复制引用的资源?

    原文 https://stackoverflow.com/questions/28240528/how-do-i-duplicate-a-resource-reference-in-code-behi ...

  8. WPF后台设置xaml控件的样式System.Windows.Style

    WPF后台设置xaml控件的样式System.Windows.Style 摘-自 :感谢 作者: IT小兵   http://3w.suchso.com/projecteac-tual/wpf-zhi ...

  9. 使用WPF来创建 Metro UI程序

    本文转载:http://www.cnblogs.com/TianFang/p/3184211.html 这个是我以前网上看到的一篇文章,原文地址是:Building a Metro UI with W ...

随机推荐

  1. C市现在要转移一批罪犯到D市,C市有n名罪犯,按照入狱时间有顺序,另外每个罪犯有一个罪行值,值越大罪越重。现在为了方便管理,市长决定转移入狱时间连续的c名犯人,同时要求转移犯人的罪行值之和不超过t,问有多少种选择的方式?

    // ConsoleApplication12.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" // ConsoleApplication1 ...

  2. 【转】Android中的Apk的加固(加壳)原理解析和实现

    一.前言 今天又到周末了,憋了好久又要出博客了,今天来介绍一下Android中的如何对Apk进行加固的原理.现阶段.我们知道Android中的反编译工作越来越让人操作熟练,我们辛苦的开发出一个apk, ...

  3. Error -27728: Step download timeout (120 seconds)的解决方法(转)

    LR中超时问题解决方法 超时错误在LoadRunner录制Web协议脚本回放时超时经常出现. 现象1:Action.c(16): Error -27728: Step download timeout ...

  4. iOS视频直播用到的协议

    一 .流媒体 1 - 伪流媒体 1.1 扫盲:边下载边播放1.2 伪流媒体:视频不是实时播放的,先把视频放在数据库,再供客户端访问,比如:优酷,爱奇艺等 1.3 特点: 边下边存,文件会保存.遵守了 ...

  5. Dominant Resource Fairness: Fair Allocation of Multiple Resource Types

    Dominant Resource Fairness: Fair Allocation of Multiple Resource Types

  6. Delphi String的散漫记录,真是知识无数,陷阱无数

    真是膜拜Delphi C++ Builder编译器的作者们,要下多少苦功夫才能解决如此之多的问题,制造出一个神级作品给世人享用.另外以我的编程经验所能想到很麻烦但却是必须的还有两个地方,一个是Form ...

  7. 【题解】NOI2015软件包管理器

    [题解][P2146 NOI2015]软件包管理器 实际上就是树链剖分板子题. 对于\(install\)操作,直接查询它到\(0\)节点有多少已经安装了的,再用总数减去它. 对于\(uninstal ...

  8. 我的Java开发学习之旅------>计算从1到N中1的出现次数的效率优化问题

    有一个整数n,写一个函数f(n),返回0到n之间出现的"1"的个数.比如f(1)=1:f(13)=6,问一个最大的能满足f(n)=n中的n是什么? 例如:f(13)=6, 因为1, ...

  9. python数据分析之:数据加载,存储与文件格式

    前面介绍了numpy和pandas的数据计算功能.但是这些数据都是我们自己手动输入构造的.如果不能将数据自动导入到python中,那么这些计算也没有什么意义.这一章将介绍数据如何加载以及存储. 首先来 ...

  10. DataGridView自定义RichTextBox列

    https://www.codeproject.com/Articles/31823/RichTextBox-Cell-in-a-DataGridView-2 RichText是用图片显示的,当Sel ...