自定义触发TextBox文本的长度

时间:2016-01-10 15:05:38

标签: c# wpf triggers

在下面的触发器中,如果TextBox Text值为空,则Border颜色为红色。

<Style TargetType="TextBox" > 
    <Style.Triggers> 
        <Trigger Property="Text" Value="">      
            <Setter Property="BorderBrush" Value="Red"/> 
        </Trigger> 
    </Style.Triggers>
</Style> 

如果文本上的长度低于4个字符,边框将为红色,我怎么能(带触发器)呢?

谢谢!

3 个答案:

答案 0 :(得分:2)

我很确定你想要实现某种验证。

不使用触发器,而是使用WPF的内置验证功能。

这样做的一种方法是在视图模型(或模型)中实现IDataErrorInfo接口。

public class MainWindowViewModel : INotifyPropertyChanged, IDataErrorInfo

Error属性实现:

public string Error { get { return null; } }

索引器的实现:

public string this[string columnName]
{
    get
    {
        if(columnName == "SomeRandomText")
        {
            if(string.IsNullOrEmpty(SomeRandomText) || SomeRandomText.Length < 4)
            {
                return "Text should be at least four characters long";
            }
        }

        return null;
    }
}

在XAML中:

<TextBox Text="{Binding SomeRandomText, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />

结果:

Result

如果您不想实施IDataErrorInfo界面,可以使用ValidationRule

使用ValidationRule

实现了同样的效果
<Binding Path="SomeRandomText" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
    <Binding.ValidationRules>
        <local:LengthValidationRule RequiredLength="4" />
    </Binding.ValidationRules>
</Binding>

ValidationRule

public class LengthValidationRule : ValidationRule
{
    public int RequiredLength { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var text = (string)value;

        if(string.IsNullOrEmpty(text) || text.Length < RequiredLength)
        {
            return new ValidationResult(false, "Text should be at least four characters long");
        }

        return ValidationResult.ValidResult;
    }
}

如果您想拥有不同的边框,可以查看Validation.ErrorTemplate附加属性。

如果你真的想用触发器做这件事,正如其他人提到的那样,你可以用一个名为LessThanConverter的转换器来做到这一点。它需要Length的{​​{1}}和您希望将其与Text进行比较的其他数字,并且会返回ConverterParameter

答案 1 :(得分:1)

如果你真的想要一个基于Style.Trigger的解决方案,你需要一个转换器:

转换器将String输入转换为布尔值,输入符合您的条件。在此示例中,文本长度必须大于4。

转换器类:

public class LengthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var text = value as string;

        if (text != null) {
            return text.Length > 4;
        }
        return false;
    }

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

}

XAML:

<Window.Resources>
    <conv:LengthConverter x:Key="converter" />
    <Style TargetType="TextBox" >
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=Text,
                    RelativeSource={RelativeSource Self},
                    Converter={StaticResource converter}}"
                    Value="False">
                <Setter Property="BorderBrush" Value="Red"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

</Window.Resources>

但正确的验证(如SzabolcsDézsi的答案)可能是更好的方法。

答案 2 :(得分:0)

参考组件: Microsoft.Expression.Interactions.dll,和 System.Windows.Interactivity.dll。 在我的机器上,它们位于: C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries

<TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="96,0,0,164.04" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Bottom">              
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="TextChanged">
                    <i:Interaction.Behaviors>
                        <ei:ConditionBehavior>
                            <ei:ConditionalExpression>
                                <ei:ComparisonCondition Operator="LessThan" RightOperand="4" LeftOperand="{Binding Text.Length, ElementName=textBox}"/>
                            </ei:ConditionalExpression>
                        </ei:ConditionBehavior>
                    </i:Interaction.Behaviors>
                    <ei:ChangePropertyAction PropertyName="BorderBrush">
                        <ei:ChangePropertyAction.Value>
                            <SolidColorBrush Color="#FFD41717"/>
                        </ei:ChangePropertyAction.Value>
                    </ei:ChangePropertyAction>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </TextBox>