ValidationRule for WPF Textbox

耗尽温柔 提交于 2019-11-29 20:55:17

问题


I am newbie to WPF.In my UserControl,I have 8 labels and its respective 8 textboxes as follows:

1.Label : abc   2.Label : def
  TextBox1 :        TextBox2 :

3.Label :xyz    4. Label : ghi
  Textbox3 :        TextBox4 :

Each of these textbox text property should contain text ending with its respective label name for TextBox1.text should be xxxx.abc, TextBox2.text should be xxxx.def and so on.if not textbox should have red border.

hope I am clear with the details.So Do i need to write different ValidationRule for each textbox??

Any you inputs??


回答1:


Why not have one ValidationRule implementation, with a property exposing what the field should end with, e.g:

public class EndsWithValidationRule : ValidationRule
{
    public string MustEndWith { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var str = value as string;
        if(str == null)
        {
            return new ValidationResult(false, "Please enter some text");
        }
        if(!str.EndsWith(MustEndWith))
        {
            return new ValidationResult(false, String.Format("Text must end with '{0}'", MustEndWith));
        }
        return new ValidationResult(true, null);

    }
}

Then you can use this like so:

<TextBox x:Name="TextBox1">
    <TextBox.Text>
        <Binding Path="BoundProperty1" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:EndsWithValidationRule MustEndWith=".def" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

<TextBox x:Name="TextBox2">
    <TextBox.Text>
        <Binding Path="BoundProperty2" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:EndsWithValidationRule MustEndWith=".abc" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>


来源:https://stackoverflow.com/questions/14481240/validationrule-for-wpf-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!