基于文本长度的 WPF 文本框背景颜色 [英] WPF Textbox Background Color based on text length

查看:21
本文介绍了基于文本长度的 WPF 文本框背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列表视图项模板中有一个文本框.每当长度大于 75 个字符时,我想将文本框的背景颜色更改为红色,并且我需要在用户键入时更新背景颜色.在 WPF 中实现这一目标的最佳方法是什么?

I have a textbox in a listview itemtemplate. I want to change the background color of the textbox to red whenever the length is greater than 75 characters, and I need the background color to update as the user types. What is the best way to achieve this in WPF?

推荐答案

我相信这样的事情会奏效.它需要您编写自己的背景颜色转换器.

I believe something like this would work. It would require you to write your own background color converter.

<TextBox 
    Background="{Binding RelativeSource={RelativeSource self},
        Path=Text, 
        UpdateSourceTrigger=PropertyChanged,
        Converter={StaticResource backgroundColorConverter}}" 
    ... 
/>

另一种选择是使用如下所示的 DataTrigger.这还需要转换器检查字符串的长度是否超过 75.

Another option would be to use a DataTrigger like below. This would also require a converter to check if the length of the string was more than 75.

<TextBox>
    ....
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Background" Value="YourDefaultColor" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=YourTextBox, Path=Text, Converter={StaticResource textLengthColorConverter}}" Value="True">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

这篇关于基于文本长度的 WPF 文本框背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆