0

I'm develepoing a Windows Phone application, and I need to validate some user inputs in text boxs. Here the XAML of one of these textbox:

<TextBox 
  Name="times" 
  Grid.Row="1" 
  Height="80"
  Text="{Binding UpdateSourceTrigger=Explicit, 
    Mode=TwoWay, 
    Path=orari,
    ValidatesOnDataErrors=True, 
    ValidatesOnExceptions=True, 
    NotifyOnValidationError=true}" 
  TextChanged="TextBoxChangedHandler"  
/>

Using BreakPoints I'm sure the IDataError finds the error, but the TextBox appereance doesn't change. I've read I should use Validate.ErrorTemplate in the XAML, but I don't find this option, pheraps it doesn't exist in Windows Phone? How can I do to change the style of the textbox if the input is not valid? Thanks

4

1 回答 1

1

很难从您发布的内容中分辨出来,但这是我的一些代码示例,它们执行非常相似的操作,也许它可以帮助您找到错误。

我要验证的文本框要使用的样式在发生错误时会显示一个红色框。

<Style x:Key="ValidationTextBox" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <Border BorderBrush="Red" BorderThickness="1">
                    <AdornedElementPlaceholder />
                </Border>
            </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>

文本框本身

<TextBox Style="{StaticResource ValidationTextBox}">
    <TextBox.Text>
        <Binding Path="Description" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <rules:MandatoryInputRule ValidatesOnTargetUpdated="True" />
                <rules:IllegalCharsRule ValidatesOnTargetUpdated="True" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

示例验证规则

class IllegalCharsRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        if (value != null)
        {
            string input = value as string;

            if (input.Contains(",") || input.Contains("/") || input.Contains(@"\") || input.Contains(".") || input.Contains("\"") || input.Contains("'"))
                return new ValidationResult(false, "Validation error. Illegal characters.");
        }

        return new ValidationResult(true, null);
    }
}
于 2012-11-09T16:52:18.690 回答