Skip to content

Commit

Permalink
Fix binding validation path
Browse files Browse the repository at this point in the history
  • Loading branch information
adegeo committed Oct 25, 2024
1 parent e3fd278 commit 1c1a903
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 89 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,29 @@ This example shows how to use an <xref:System.Windows.Controls.Validation.ErrorT

The text content of the <xref:System.Windows.Controls.TextBox> in the following example is bound to the `Age` property (of type int) of a binding source object named `ods`. The binding is set up to use a validation rule named `AgeRangeRule` so that if the user enters non-numeric characters or a value that is smaller than 21 or greater than 130, a red exclamation mark appears next to the text box and a tool tip with the error message appears when the user moves the mouse over the text box.

[!code-xaml[BindValidation#2](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#2)]
[!code-xaml[BindValidation#2](../../../samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#2)]

The following example shows the implementation of `AgeRangeRule`, which inherits from <xref:System.Windows.Controls.ValidationRule> and overrides the <xref:System.Windows.Controls.ValidationRule.Validate%2A> method. The `Int32.Parse` method is called on the value to make sure that it does not contain any invalid characters. The <xref:System.Windows.Controls.ValidationRule.Validate%2A> method returns a <xref:System.Windows.Controls.ValidationResult> that indicates if the value is valid based on whether an exception is caught during the parsing and whether the age value is outside of the lower and upper bounds.

[!code-csharp[BindValidation#3](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/AgeRangeRule.cs#3)]
[!code-vb[BindValidation#3](~/samples/snippets/visualbasic/VS_Snippets_Wpf/BindValidation/VisualBasic/AgeRangeRule.vb#3)]
[!code-csharp[BindValidation#3](../../../samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/AgeRangeRule.cs#3)]
[!code-vb[BindValidation#3](../../../samples/snippets/visualbasic/VS_Snippets_Wpf/BindValidation/VisualBasic/AgeRangeRule.vb#3)]

The following example shows the custom <xref:System.Windows.Controls.ControlTemplate> `validationTemplate` that creates a red exclamation mark to notify the user of a validation error. Control templates are used to redefine the appearance of a control.

[!code-xaml[BindValidation#4](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#4)]
[!code-xaml[BindValidation#4](../../../samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#4)]

As shown in the following example, the <xref:System.Windows.Controls.ToolTip> that shows the error message is created using the style named `textBoxInError`. If the value of <xref:System.Windows.Controls.Validation.HasError%2A> is `true`, the trigger sets the tool tip of the current <xref:System.Windows.Controls.TextBox> to its first validation error. The <xref:System.Windows.Data.Binding.RelativeSource%2A> is set to <xref:System.Windows.Data.RelativeSourceMode.Self>, referring to the current element.

[!code-xaml[BindValidation#5](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#5)]
[!code-xaml[BindValidation#5](../../../samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#5)]

## Data object

The following snippet is the data object used in the previous code examples. An instance is created in the XAML as a static resource with the name of `ods`:

:::code language="csharp" source="../../../samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/MyDataSource.cs" id="DataSource":::
:::code language="vb" source="../../../samples/snippets/visualbasic/VS_Snippets_Wpf/BindValidation/VisualBasic/MyDataSource.vb" id="DataSource":::

## Complete example

For the complete example, see [Bind Validation sample](https://github.com/Microsoft/WPF-Samples/tree/master/Data%20Binding/BindValidation).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,14 @@ public class AgeRangeRule : ValidationRule
public int Min { get; set; }
public int Max { get; set; }

public AgeRangeRule()
{
}

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int age = 0;

try
{
if (((string)value).Length > 0)
age = Int32.Parse((String)value);
age = int.Parse((String)value);
}
catch (Exception e)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<!-- MSBUILD Project File -->
<PropertyGroup>
<BuildSystem>MSBuild</BuildSystem>
Expand All @@ -12,22 +12,25 @@
<ProductVersion>10.0.20821</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{950D18C5-F942-494B-87F5-DE051442ABF6}</ProjectGuid>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>.\bin\Debug\</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugSymbols>false</DebugSymbols>
<Optimize>true</Optimize>
<OutputPath>.\bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<ItemGroup>
Expand Down Expand Up @@ -70,4 +73,7 @@
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,18 @@

namespace SDKSample
{
//<DataSource>
public class MyDataSource
{
private int _age;
private int _age2;
private int _age3;

public MyDataSource()
{
Age = 0;
Age2 = 0;
}

public int Age
{
get { return _age; }
set { _age = value; }
}
public int Age2
{
get { return _age2; }
set { _age2 = value; }
}

public int Age3
{
get { return _age3; }
set { _age3 = value; }
}
public int Age { get; set; }
public int Age2 { get; set; }
public int Age3 { get; set; }
}
//</DataSource>
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample"
xmlns:local="clr-namespace:SDKSample"
x:Class="SDKSample.Window1"
Title="Binding Validation Sample"
SizeToContent="WidthAndHeight"
ResizeMode="NoResize">

<!--<Snippet1>-->
<Window.Resources>
<c:MyDataSource x:Key="ods"/>
<local:MyDataSource x:Key="ods"/>

<!--<Snippet4>-->
<ControlTemplate x:Key="validationTemplate">
Expand All @@ -25,8 +25,8 @@
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)/ErrorContent}"/>
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
Expand Down Expand Up @@ -65,7 +65,7 @@
<Binding Path="Age" Source="{StaticResource ods}"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<c:AgeRangeRule Min="21" Max="130"/>
<local:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
Expand All @@ -81,7 +81,7 @@
<Binding Path="Age2" Source="{StaticResource ods}"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<c:AgeRangeRule Min="21" Max="130"/>
<local:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
Expand All @@ -21,8 +21,9 @@
<IsWebBootstrapper>true</IsWebBootstrapper>
<BootstrapperEnabled>true</BootstrapperEnabled>
<PublishUrl>Publish\</PublishUrl>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<ProductVersion>10.0.20821</ProductVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
Expand All @@ -34,6 +35,7 @@
<OutputPath>bin\</OutputPath>
<DocumentationFile>BindValidation_VB.xml</DocumentationFile>
<NoWarn>42016,42017,42018,42019,42032,42314</NoWarn>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugSymbols>false</DebugSymbols>
Expand All @@ -44,6 +46,7 @@
<OutputPath>bin\</OutputPath>
<DocumentationFile>BindValidation_VB.xml</DocumentationFile>
<NoWarn>42016,42017,42018,42019,42032,42314</NoWarn>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
Expand Down Expand Up @@ -110,5 +113,8 @@
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project>
Original file line number Diff line number Diff line change
@@ -1,43 +1,12 @@
Public Class MyDataSource
' Methods
Public Sub New()
Me.Age = 0
Me.Age2 = 0
End Sub


' Properties
Public Property Age As Integer
Get
Return Me._age
End Get
Set(ByVal value As Integer)
Me._age = value
End Set
End Property

Public Property Age2 As Integer
Get
Return Me._age2
End Get
Set(ByVal value As Integer)
Me._age2 = value
End Set
End Property

Public Property Age3 As Integer
Get
Return Me._age3
End Get
Set(ByVal value As Integer)
Me._age3 = value
End Set
End Property


' Fields
Private _age As Integer
Private _age2 As Integer
Private _age3 As Integer
End Class

'<DataSource>
Public Class MyDataSource
Public Sub New()
Me.Age = 0
Me.Age2 = 0
End Sub

Public Property Age As Integer
Public Property Age2 As Integer
Public Property Age3 As Integer
End Class
'</DataSource>
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:BindValidation_VB"
xmlns:local="clr-namespace:BindValidation_VB"
x:Class="Window1"
Title="Binding Validation Sample"
SizeToContent="WidthAndHeight"
ResizeMode="NoResize">

<Window.Resources>
<c:MyDataSource x:Key="ods"/>
<local:MyDataSource x:Key="ods"/>

<ControlTemplate x:Key="validationTemplate">
<DockPanel>
Expand Down Expand Up @@ -57,7 +57,7 @@
<Binding Path="Age" Source="{StaticResource ods}"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<c:AgeRangeRule Min="21" Max="130"/>
<local:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
Expand All @@ -71,7 +71,7 @@
<Binding Path="Age2" Source="{StaticResource ods}"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<c:AgeRangeRule Min="21" Max="130"/>
<local:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
Expand Down

0 comments on commit 1c1a903

Please sign in to comment.