Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3488164
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T11:14:15+00:00 2026-05-18T11:14:15+00:00

I have a custom ValidationRule that requires access to the ViewModel in order to

  • 0

I have a custom ValidationRule that requires access to the ViewModel in order to validate a supplied value in conjunction with other properties of the ViewModel. I previously tried to acheive this by using a ValidationGroup, but abandoned this idea as the code I am modifying would need a lot of refactoring in order to enable this route.

I found a thread on a newsgroup that showed a way of binding the DataContext of a control in which the ValidationRule is being run to that ValidationRule by way of an intermediate class inherited from DependencyObject, but I cannot get it to bind.

Can anybody help?

My ValidationRule is as follows…

class TotalQuantityValidator : CustomValidationRule {

    public TotalQuantityValidator()
        : base(@"The total number must be between 1 and 255.") {
    }

    public TotalQuantityValidatorContext Context { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo) {

        ValidationResult validationResult = ValidationResult.ValidResult;

        if (this.Context != null && this.Context.ViewModel != null) {

            int total = ...
            if (total <= 0 || total > 255) {
                validationResult = new ValidationResult(false, this.ErrorMessage);
            }

        }

        return validationResult;

    }

}

CustomValidationRule is defined as follows…

public abstract class CustomValidationRule : ValidationRule {

    protected CustomValidationRule(string defaultErrorMessage) {
        this.ErrorMessage = defaultErrorMessage;
    }

    public string ErrorMessage { get; set; }

}

TotalQuantityValidatorContext is defined as follows…

public class TotalQuantityValidatorContext : DependencyObject {

    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(@"ViewModel",
        typeof(MyViewModel), typeof(TotalQuantityValidatorContext),
        new PropertyMetadata {
            DefaultValue = null,
            PropertyChangedCallback = new PropertyChangedCallback(TotalQuantityValidatorContext.ViewModelPropertyChanged)
        });

    public MyViewModel ViewModel {
        get { return (MyViewModel)this.GetValue(TotalQuantityValidatorContext.ViewModelProperty); }
        set { this.SetValue(TotalQuantityValidatorContext.ViewModelProperty, value); }
    }

    private static void ViewModelPropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs args) {
    }

}

And the whole thing is used thus…

<UserControl x:Class="..."
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:val="clr-namespace:Validators" x:Name="myUserControl">

    <TextBox Name="myTextBox">
        <TextBox.Text>
            <Binding NotifyOnValidationError="True" Path="myViewModelProperty" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <val:TotalQuantityValidator>
                        <val:TotalQuantityValidator.Context>
                            <val:TotalQuantityValidatorContext ViewModel="{Binding ElementName=myUserControl, Path=DataContext}" />
                        </val:TotalQuantityValidator.Context>
                    </val:TotalQuantityValidator>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

</UserControl>

The DataContext of the UserControl is being set to an instance of MyViewModel in code-behind. I know that this binding works as the standard control bindings are operating as expected.

The TotalQuantityValidator.Validate method is called correctly, but whenever I look at the ViewModel property of the Context, it is always null (the Context property of the TotalQuantityValidator is being set to an instance of TotalQuantityValidatorContext correctly). I can see from the debugger however that the setter on the ViewModel property of the TotalQuantityValidatorContext is never called.

Can anybody advise as to how I can get this binding to work?

Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T11:14:15+00:00Added an answer on May 18, 2026 at 11:14 am

    I would avoid using validation rules. If you need access to the information in the viewmodel to perform validation, then it’s better to put the validation logic in the viewmodel itself.

    You can make your viewmodel implement IDataErrorInfo, and simply turn on data error info-based validation on the binding.

    Even if you don’t run into this (very common) problem of needing contextual information, validation rules aren’t really a great way to express validation: validation rules are usually related to business logic, or at least to semantic aspects of your information. Xaml seems like the wrong place to put such things – why would I put a business rule in the source file whose main job is to determine the layout and visual design of my application?

    Validation logic belongs further down in your app. Even the viewmodel might be the wrong layer, but in that case, you can simply make it the viewmodel’s responsibility to work out where to find the validation logic.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a few models that need to have custom find conditions placed on
I have a custom control that implements IPostBackEventHandler. Some client-side events invoke __doPostBack(controlID, eventArgs).
I have a custom installer action that updates the PATH environment, and creates an
We have a custom-built Flash-based video player that I maintain, and it needs to
I have custom classes that I currently instantiate within App.xaml as resources. I want
I have a custom converter that has a DefaultText property. All my converter does
I have custom validators and filters that I have created that I would like
I have custom coded several enterprise applications for mid to large organizations to use
I have custom errors configured in my web.config, but IIS 6.0 is returning the
Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators? For

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.