Use the data verification mechanism provided by WPF

Source: Internet
Author: User

When you provide the required data through the WPF dialog box, the dialog box ensures that the provided data is valid for the following reasons:

  • From a security perspective, all inputs should be verified.

  • From a domain-specific perspective, data verification can prevent the code from processing incorrect data, because this may cause exceptions.

  • From the perspective of user experience, the dialog box can help users by displaying to users which input data is invalid.

  • From a performance perspective, data verification in a multi-tier application can reduce the number of rounds between the client and the application layer, especially when the application is composed of a Web service or a server-based database.

To verify the bound control in WPF, You need to define the verification rule and associate it with the binding. The validation rule is a custom class derived from validationrule. The following example demonstrates the validation rule marginvalidationrule, which checks whether the bound value is double and whether it is within the specified range.

C #

Using system. Globalization;
Using system. Windows. controls;

Namespace sdksample
{
Public class marginvalidationrule: validationrule
{
Double minmargin;
Double maxmargin;

Public double minmargin
{
Get {return this. minmargin ;}
Set {This. minmargin = value ;}
}

Public double maxmargin
{
Get {return this. maxmargin ;}
Set {This. maxmargin = value ;}
}

Public override validationresult validate (object value, cultureinfo)
{
Double margin;

// Is a number?
If (! Double. tryparse (string) value, out margin ))
{
Return new validationresult (false, "not a number .");
}

// Is in range?
If (margin <this. minmargin) | (margin> This. maxmargin ))
{
String MSG = string. Format ("margin must be between {0} and {1}.", this. minmargin, this. maxmargin );
Return new validationresult (false, MSG );
}

// Number is valid
Return new validationresult (true, null );
}
}
}

In this Code, the validation logic of the validation rule is implemented by rewriting the validate method. This method verifies the data and returns the corresponding validationresult.

To associate a verification rule with a bound control, use the following tag.

XAML

<Window     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    x:Class="SDKSample.MarginsDialogBox"    xmlns:local="clr-namespace:SDKSample"    Title="Margins"    Height="190"    Width="300"    MinHeight="10"    MinWidth="300"    ResizeMode="CanResizeWithGrip"    ShowInTaskbar="False"    WindowStartupLocation="CenterOwner"     FocusManager.FocusedElement="{Binding ElementName=leftMarginTextBox}">  <Grid>...<Label Grid.Column="0" Grid.Row="0">Left Margin:</Label><TextBox Name="leftMarginTextBox" Grid.Column="1" Grid.Row="0">  <TextBox.Text>    <Binding Path="Left" UpdateSourceTrigger="PropertyChanged">      <Binding.ValidationRules>        <local:MarginValidationRule MinMargin="0" MaxMargin="10" />      </Binding.ValidationRules>    </Binding>  </TextBox.Text></TextBox>...</Window>

After a verification rule is associated, WPF automatically applies the rule when the control is bound to the data input. If the control contains invalid data, WPF displays a red border around the invalid control, as shown in.

Before a user inputs valid data, WPF does not restrict the user from invalid controls. This is very advantageous for the dialog box. No matter whether the data is valid or not, the user should be able to freely navigate the control in the dialog box. However, this means that the user can enter invalid data and then press "OK. Therefore, when you press the "OK" button, your code also needs to process the click event to verify all the controls in the dialog box.

C #

Using system. Windows; // window, routedeventargs, iinputelement, dependencyobject
Using system. Windows. controls; // Validation
Using system. Windows. input; // keyboard

Namespace sdksample
{
Public partial class marginsdialogbox: Window
{

...

Void okbutton_click (Object sender, routedeventargs E)
{
// Don't accept the dialog box if there is invalid data
If (! Isvalid (this) return;

...

}

// Validate all dependency objects in a window
Bool isvalid (dependencyobject node)
{
// Check if dependency object was passed
If (node! = NULL)
{
// Check if dependency object is valid.
// Note: validation. gethaserror works for controls that have validation rules attached
Bool isvalid =! Validation. gethaserror (node );
If (! Isvalid)
{
// If the dependency object is invalid, and it can receive the focus,
// Set the focus
If (node is iinputelement) keyboard. Focus (iinputelement) node );
Return false;
}
}

// If this dependency object is valid, check all child dependency objects
Foreach (Object subnode in logicaltreehelper. getchildren (node ))
{
If (subnode is dependencyobject)
{
// If a child dependency object is invalid, return false immediately,
// Otherwise keep checking
If (isvalid (dependencyobject) subnode) = false) return false;
}
}

// All dependency objects are valid
Return true;
}
}
}

This code will enumerate all dependency objects in the window. If any object is invalid (returned by gethaserror), the invalid control gets the focus. The isvalid method returns false and the window is considered invalid.

Once the dialog box is valid, it can be safely closed and returned. In the return process, a result must be returned to the called function.

This article is from msdn and everything belongs to msdn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.