簡體   English   中英

驗證錯誤模板不顯示錯誤結果 WPF

[英]Validation Error template doesn't show the Error result WPF

我是 WPF 新手我想驗證我的 IP 地址,但我有一個問題:當我嘗試顯示錯誤消息時,它只顯示一個空的紅色邊框。

這是ControlTemplate和所有代碼:

<Window x:Class="SOTCBindingValidation.Window1"
        x:Name="This"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SOTCBindingValidation"
        Title="SOTC Validation Test" Height="150" Width="400">
  <Window.Resources>
    <local:ErrorsToMessageConverter x:Key="eToMConverter"/>

    <ControlTemplate x:Key="customvalidatortemplate">
      <StackPanel Orientation="Horizontal">
        <Border BorderThickness="1" BorderBrush="Red" VerticalAlignment="Top">
          <Grid>
            <AdornedElementPlaceholder x:Name="adorner" Margin="-1"/>
          </Grid>
        </Border>
        <Border x:Name="errorBorder" Background="Red" Margin="8,0,0,0"
                CornerRadius="0" IsHitTestVisible="False">
          <TextBlock Text="{Binding ElementName=AddressBox, 
                     Path=(Validation.Errors),
                     Converter={StaticResource eToMConverter}}" 
                     Foreground="White" FontFamily="Segoe UI"
                     Margin="8,2,8,3" TextWrapping="Wrap"
                     VerticalAlignment="Center"/>
        </Border>
      </StackPanel>
    </ControlTemplate>         
  </Window.Resources>

  <StackPanel Margin="5">
    <TextBlock Margin="2">Enter An IPv4 Address:</TextBlock>
    <TextBox x:Name="AddressBox"
             Validation.ErrorTemplate="{StaticResource customvalidatortemplate}"
             Margin="0,0,235.5,0">
      <TextBox.Text>
        <Binding ElementName="This" Path="IPAddress" 
                 UpdateSourceTrigger="PropertyChanged">
          <Binding.ValidationRules>
            <local:IPv4ValidationRule/>
          </Binding.ValidationRules>
        </Binding>
      </TextBox.Text>
    </TextBox>    
  </StackPanel>
</Window>

ErrorsToMessageConverter.cs 文件:

public class ErrorsToMessageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var sb = new StringBuilder();
        var errors = value as ReadOnlyCollection<ValidationError>;
        if (errors != null)
        {
            foreach (var e in errors.Where(e => e.ErrorContent != null))
            {
                sb.AppendLine(e.ErrorContent.ToString());
            }
        }

        return sb.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

IPv4ValidationRule.cs 文件:

public class IPv4ValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var str = value as string;
        if (String.IsNullOrEmpty(str))
        {
            return new ValidationResult(false,
                "Please enter an IP Address.");
        }

        var parts = str.Split('.');
        if (parts.Length != 4)
        {
            return new ValidationResult(false,
                "IP Address should be four octets, seperated by decimals.");
        }
        foreach (var p in parts)
        {
            int intPart;
            if (!int.TryParse(p, NumberStyles.Integer, cultureInfo.NumberFormat, out intPart))
            {
                return new ValidationResult(false,
                    "Each octet of an IP Address should be a number.");
            }

            if (intPart < 0 || intPart > 255)
            {
                return new ValidationResult(false,
                    "Each octet of an IP Address should be between 0 and 255.");
            }
        }

        return new ValidationResult(true, null);
    }
}

我找到了解決方案(睡了一覺后:)。 實際上,您必須綁定到的確切元素源可以通過AdornedElementPlaceholder訪問。 它有一個叫做財產AdornedElementTemplateBinding不起作用在這種情況下,因為TemplatedParent不指向TextBox ,它只是一個控制它用於ErrorTemplate控制。 所以代碼應該是這樣的:

<TextBlock Text="{Binding ElementName=adorner, 
                          Path=AdornedElement.(Validation.Errors),
                          Converter={StaticResource eToMConverter}}" 
           Foreground="White" FontFamily="Segoe UI" Margin="8,2,8,3" 
           TextWrapping="Wrap" VerticalAlignment="Center"/>

請注意我們如何為AdornedElement設置附加屬性Validation.Errors 還要注意名稱adorner ,它正是您為AdornedElementPlaceholder設置的名稱。 我做了一個演示,它肯定可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM