繁体   English   中英

在UWP c#中选择或点击文本框后,如何更改文本框前景的颜色?

[英]How Change color of the textbox foreground after select or tap on the textbox in UWP c#?

在UWP中选择或点击文本框后,如何更改文本框前景的颜色?

我在文本框的getfocus事件上使用了以下代码。

private void tbWeight_GotFocus(object sender, RoutedEventArgs e) 
{ 
  tbWeight.Foreground = new SolidColorBrush(Colors.blue); 
}

第一次,当我在文本框上写一些东西时,它的工作正常,但是当文本框失去焦点,然后在同一文本框上再次点击或获取光标时,字体颜色将变为黑色。 我想将黑色更改为蓝色或任何其他颜色。

有什么问题吗

当您将Foreground属性设置为TextBox ,仅当TextBox失去焦点时才应用此颜色,因此当您获得它的光标时,此颜色将不会更改。 这就是为什么您的代码首次起作用的原因。

然后,在LostFocus事件中,将前景更改为其原始颜色。 它使您的前景在获得焦点时发生更改,并在失去焦点时再次发生变化,但是仅当TextBox失去焦点时才应用前景颜色,这使您的代码似乎永远无法工作。

进行此工作的正确方法是修改TextBox的模板,可以打开“ 文档大纲”,然后找到您的TextBox ,右键单击它并选择“ 编辑模板” ,最后选择“ 编辑副本” ,然后将生成TextBox的默认样式在Page.Resources 在这种样式下,您可以找到VisualState x:Name="Focused" ,在这种视觉状态下,它控制TextBox聚焦时的前景,您可以像这样更改它:

<VisualState x:Name="Focused">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundFocused}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushFocused}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Blue" /> <!--This one here!-->
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="RequestedTheme" Storyboard.TargetName="ContentElement">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Light" />
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM