(1) 列表控件绑定数据对象集合
<ListBox Name="lstProducts" Margin="5" DisplayMemberPath="ModelName"/>
(2) Grid控件绑定到列表元素,指定为选中的对象,并做错误检查
<Grid Name="gridProductDetails" DataContext="{Binding ElementName=lstProducts, Path=SelectedItem}" Validation.Error="validationError">
设置Grid的资源:
<Grid.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="14" FontWeight="Bold"
ToolTip="{Binding ElementName=adornerPlaceholder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">*</TextBlock>
<Border BorderBrush="Green" BorderThickness="1">
<AdornedElementPlaceholder Name="adornerPlaceholder"></AdornedElementPlaceholder>
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
(3) 在Grid中的文本控件绑定对象的属性值,做数据有效性的检查
<TextBox Margin="5" Grid.Column="1">
<TextBox.Text>
<Binding Path="ModelNumber" NotifyOnValidationError="true">
<Binding.ValidationRules>
<DataErrorValidationRule></DataErrorValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<TextBox Margin="5" Grid.Row="2" Grid.Column="1">
<TextBox.Text>
<Binding Path="UnitCost" NotifyOnValidationError="true" StringFormat="{}{0:C}">
<Binding.ValidationRules>
<local:PositivePriceRule Max="999.99"></local:PositivePriceRule>
<ExceptionValidationRule></ExceptionValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
(4)检查类
using System.Windows.Controls;
using System.Globalization;
namespace WpfApp
{
public class PositivePriceRule : ValidationRule
{
private decimal min = 0;
private decimal max = Decimal.MaxValue;
public decimal Min
{
get { return min; }
set { min = value; }
}
public decimal Max
{
get { return max; }
set { max = value; }
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
decimal price = 0;
try
{
if (((string)value).Length > 0)
//Allow number styles with currency symbols like $
price = decimal.Parse((string)value, System.Globalization.NumberStyles.Any);
}
catch (Exception e)
{
return new ValidationResult(false, "Illegal characters");
}
if ((price < min) || (price > Max))
{
return new ValidationResult(false, "NOT in the reange " + Min + " to " + Max);
}
else
{
return new ValidationResult(true, null);
}
}
}
}
效果如下:
网友评论