首页 > 解决方案 > C# UWP 如何更改 TextBox 的前景

问题描述

如果更改文本,如何更改 TextBox 的前景?例如,我将写“zzz”,前景将更改为“Red”。

    <StackPanel Grid.Column="1" Margin="10">
        <TextBox Width="200" Text="asdasd" x:Name="qwerty">

        </TextBox>
    </StackPanel>

标签: c#uwp

解决方案


首先,您需要将Foregroundand添加TextChanged到 TextBox:

<TextBox Foreground="{DynamicResource txtColor}" Width="200" Text="asdasd" x:Name="qwerty" TextChanged="TextBox1_TextChanged">

</TextBox>

然后您可以在 TextChanged 事件中动态更改文本框的前景,如下所示:

private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox textBox = sender as TextBox;
    if(textBox.Text == "zzz")
    {
        Application.Current.Resources["txtColor"] = new SolidColorBrush(Colors.Red);
    }
}

推荐阅读