【问题标题】:How to do validation for a mandatory field without using Binding Path如何在不使用绑定路径的情况下对必填字段进行验证
【发布时间】:2013-03-18 11:02:06
【问题描述】:

我现在的问题是, 对于我目前拥有的每个文本框,我必须指定一个绑定路径以验证文本框是否为空。 但是,如果碰巧我有一百个文本框,我不可能为所有 100 个文本框单独创建一个获取和设置方法。那么有没有更好的方法来进行我现在的当前验证?

以下是我目前拥有的代码,

在 XAML 中

 <Grid.BindingGroup>
            <BindingGroup Name="RequiredFields">
                <BindingGroup.ValidationRules>
                    <local:MandatoryFieldRule ValidationStep ="CommittedValue"/>
                </BindingGroup.ValidationRules>
            </BindingGroup>
        </Grid.BindingGroup>
            <TextBox x:Name="ds_instruct" HorizontalAlignment="Left" Height="30"
               Margin="286,186,0,0" TextWrapping="Wrap" VerticalAlignment="Top"    
               Width="275" FontSize="11" GotFocus="textBox_Expand"                                                     
               LostFocus="textBox_Expand" Tag="Default Special Instruction" 
               SpellCheck.IsEnabled="True" 
               Text="{Binding  Path=Text, BindingGroupName=RequiredFields,ValidatesOnDataErrors=true}"/>

在验证文件中:

public String Text { get; set; }
public String Text1 { get; set; }

 #region IDataErrorInfo Members
   public string Error
    {
        get {throw new NotImplementedException(); }
    }

    public string this[string columnName]
    {
        get 
        {
            string result = null;
            if (columnName == "Text")
            {
                if (string.IsNullOrEmpty(Text))
                {result = "Mandatory field required"; }
            }
            if (columnName == "Text1")
            {
                if (string.IsNullOrEmpty(Text1))
                { result = "Mandatory field required"; }
            }
            return result;

        }

    }

    #endregion

所以我的问题是,如何在不指定一对一绑定的情况下验证多个文本框的必填字段(文本框到 getter 和 setter 方法)?

提前谢谢大家!

【问题讨论】:

  • 您如何在运行时创建文本框(100 个)?还是上面的xaml是你复用的用户控件?
  • 嗨,Jacob,在某种程度上,我的意思是,对于绑定路径,是否可以在不指定 get 和 set 方法的情况下从文本中获取值?
  • 就绑定而言,UI-TextBox 中的每个元素都应该绑定到一个属性,它可以是相同的或不同的属性。可以遍历加载的控件吗?但在这里你可能需要为每个控件指定验证。
  • 你可以试试这个Binding Validation:msdn.microsoft.com/en-IN/library/ms753962.aspx。这将帮助您编写自定义验证器。在运行时,每当您创建新的 TextBox 挂钩/将其验证器绑定到您创建的自定义验证器时。
  • 嗨,jacob,有趣的想法,但我放弃并为每个元素指定了一个属性,创建了一个实体模型来存储它。这是因为我必须对每个元素进行数据验证用户控制字段。谢谢你的建议,我改天试试

标签: c# wpf xaml


【解决方案1】:

也许你可以使用Reflection 来检查字符串的值

public string this[string columnName]
{
    get 
    {
        string result = null;
        if (string.IsNullOrEmpty(this.GetType().GetProperty(columnName).GetValue(this) as string))
        {
            result = "Mandatory field required";
        }
        return result;
    }
}

【讨论】:

    猜你喜欢
    • 2021-06-22
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多