开发者

WPF Textbox Background Color based on text length

开发者 https://www.devze.com 2022-12-14 17:04 出处:网络
I have a textbox in a listview itemtemplate.I开发者_C百科 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 t

I have a textbox in a listview itemtemplate. I开发者_C百科 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}}" 
    ... 
/>

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>


You can make use of "Run" tag with in text block, which applies background according to length of text


0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号