WPF 的验证器 转换器
in 默认分类 with 0 comment

验证器

使用验证器的时候 需要用绑定的完整写法

<TextBox FontSize="30" x:Name="ttt">
    <TextBox.Text>
    <Binding Path="TestText"
        UpdateSourceTrigger="PropertyChanged">
        <Binding.ValidationRules>
            <local:TestValidtionRule ValidatesOnTargetUpdated="True" />
        </Binding.ValidationRules>
    </Binding>
    </TextBox.Text>
</TextBox>

代码的类需要继承自 ValidationRule

public class TestValidtionRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value != null) {
            string? s = value.ToString();
            if (s != null && s.Length > 1 && s.Length <= 10) {
                return new ValidationResult(true, "通过");
            }
        }
        return new ValidationResult(false, "用户名长度1-10个字符");
    }
}

错误文本需要显示的话 有很多方法 给一个例子
这里的绑定用到了括号绑定(绑定附加属性就需要用到括号)

<TextBlock Text="{Binding ElementName=ttt,Path=(Validation.Errors)[0].ErrorContent}"/>

转换器

绑定的时候直接指定 需要定义资源 然后通过资源绑定

<TextBlock FontSize="30" Text="{Binding TestText, Converter={StaticResource MyConverter}}"/>

要在资源里面定义

<Window.Resources>
    <local:MyValueConverter x:Key="MyConverter"/>
</Window.Resources>

后台代码的类需要继承自IValueConverter,实现Convert和ConvertBack方法

public class MyValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string str) {
            string s = str.ToString();
            if (s == "") {
                return "空值";
            } else if (s == "哈哈哈") {
                return "小哈哈哈";
            } else {
                return "不明白";
            }
        }
        throw new NotImplementedException();

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string str) {
            string s = str.ToString();
            if (s == "") {
                return "空值";
            } else if (s == "哈哈哈") {
                return "小哈哈哈";
            } else {
                return "不明白";
            }
        }

        throw new NotImplementedException();
    }
}

闪烁效果

<TextBlock Width="200"
        Height="50" Text="456">
  <TextBlock.Style>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Foreground"
              Value="#FF3BA245" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding IsAnimation}"
                      Value="True">
          <DataTrigger.EnterActions>
            <BeginStoryboard x:Name="stateAnimation">
              <Storyboard AutoReverse="True"
                          RepeatBehavior="Forever">
                <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground.(SolidColorBrush.Color)">
                  <EasingColorKeyFrame KeyTime="0"
                                        Value="White" />
                  <EasingColorKeyFrame KeyTime="00:00:0.5"
                                        Value="Red" />
                </ColorAnimationUsingKeyFrames>
              </Storyboard>
            </BeginStoryboard>
          </DataTrigger.EnterActions>
          <DataTrigger.ExitActions>
            <StopStoryboard BeginStoryboardName="stateAnimation" />
          </DataTrigger.ExitActions>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBlock.Style>
</TextBlock>