开发者

WPF Validation on two properties

开发者 https://www.devze.com 2022-12-28 18:06 出处:网络
I have a user control that contains a border somewhere in it. I am able to edit both the User Control Width and the Border Width from bindi开发者_开发知识库ng to two textboxes. I need to include valid

I have a user control that contains a border somewhere in it. I am able to edit both the User Control Width and the Border Width from bindi开发者_开发知识库ng to two textboxes. I need to include validation when I create the binding in code so that the Border Width can't be higher than the User Control Width.


Using dependency property you can achive this. Create a dependency property on your Border Width and when ever there will be change to this property it will be called and you can check whether the width is greater then the usercontrol width if its true you can throw validation.


I solved my problem, it was kind of easy, I thought of deleting my question better than respond to it, but maybe someone will find this useful.

class MyUserControlValidationRule : ValidationRule
{
    private MyUserControl _control;
    public MyUserControlValidationRule(MyUserControl control)
    {
        _control = control;
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        int parameter = 0;
        try
        {
            if (((string)value).Length > 0)
            {
                parameter = int.Parse((String)value);
            }
        }
        catch (Exception e)
        {
            return new ValidationResult(false, "Illegal characters or " + e.Message);
        }

        if (parameter >= _control.Width)
        {
            return new ValidationResult(false, "Border width is bigger that the control width.");
        }
        return new ValidationResult(true, null);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号