mrhands
mrhands

Reputation: 1533

How to make separated validation in WPF Application in Windows application

I want to make validation in a separated xaml definition with my own custom code in C# to make windows form. I have been read the resource about code like this validation with custom validation

 <Window  xmlns:validators="clr-namespace:MyValidators" [...]/>

and then this is the xaml definition with custom code

  <TextBox x:Name="textAge">
    <TextBox.Text>
        <Binding Path="Name">
            <Binding.ValidationRules>
              <validators:StringRangeValidationRule 
                 MinimumLength="1" 
                 ErrorMessage="Age is required." />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

But I want the validation become like this

<TextBox x:Name="textAge" Text="{Binding Path=Age}"/>

And in separate file I want to define my own validation for example Validation.xml

<validation:StringrangeValidationRule target="textAge"  MinimumLength="1" errorMessage="Age is required" />

How I can accomplish this I have so many textBox with different validation rules. I don't want to mix up the definition of textbox and validation in one place that can make me hard to read the code...

Any help regards..

Upvotes: 0

Views: 310

Answers (2)

obaylis
obaylis

Reputation: 3034

Why not use the Enterprise Library Validation application block. You can then specify validation on your object properties via attributes or configuration (in a separate, non-compiled XML file).

Your XAML then looks like this:

<TextBox Text="{Binding SomeName, ValidatesOnDataErrors=True}"/>

There is a new version of Enterprise Library (version 6) that was released in April this year.

These hands-on labs from Microsoft give a good walkthrough of how to get you started (it's for an earlier version but the principles are the same).

Upvotes: 0

Jatin
Jatin

Reputation: 4063

You can put the Binding and the validation rule in a keyed style and assign that to text box. Here is an example

<Window.Resources>
    <Style x:Key="SomeNameTextBoxStyle" TargetType="{x:Type TextBox}">
        <Style.Setters>
            <Setter Property="Text">
                <Setter.Value>
                    <Binding Path="SomeName">
                        <Binding.ValidationRules>
                            <validators:StringRangeValidationRule 
                                 MinimumLength="1" 
                                 ErrorMessage="SomeName is required." />
                        </Binding.ValidationRules>
                    </Binding>
                </Setter.Value>
            </Setter>
        </Style.Setters>
    </Style>
</Window.Resources>

Assign this style to the textbox

<TextBox Style="{StaticResource SomeNameTextBoxStyle}"/>

I think this should work. However I would suggest you to also look at IDataErrorInfo interface which also provides a way to validate properties.

Upvotes: 1

Related Questions