【问题标题】:How Change color of the textbox foreground after select or tap on the textbox in UWP c#?在 UWP c# 中选择或点击文本框后如何更改文本框前景的颜色?
【发布时间】:2016-08-25 14:17:44
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您能提供更多代码吗?
  • private void tbWeight_GotFocus(object sender, RoutedEventArgs e) { tbWeight.Foreground = new SolidColorBrush(Colors.blue); }
  • 有什么问题吗..

标签: xaml c#-4.0 uwp uwp-xaml


【解决方案1】:

有什么问题

当您将Foreground 属性设置为TextBox 时,该颜色只会在TextBox 失去焦点时应用,因此当您获得它的光标时,该颜色不会改变。这就是您的代码第一次运行的原因。

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

正确的做法是修改TextBox的模板,你可以打开文档大纲找到你的TextBox,右键选择编辑模板,最后选择Edit a copyPage.Resources中就会生成你TextBox的默认样式。在这种风格下,你可以找到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>

【讨论】:

  • @TrishitBera,也许我有点误解了你的问题,但是即使你设置了前景,当TextBox获得焦点时,前景将恢复为原来的颜色,它定义在视觉状态...这就是为什么我建议你在TextBox的模板中编辑视觉状态。
  • 是他们解决这个问题的任何简单方法。因为它填满了我的 xaml 页面。 :)
  • @TrishitBera,你可以在你的 app.xaml 中覆盖SystemControlForegroundChromeBlackHighBrush,但这会改变整个系统刷。或者你可以用 vs blend 来修改这个,这个操作对某些人来说可能更容易,但最终这个值应该被修改,AFAIK,这已经是最简单的方法了......
  • 感谢您的帮助和时间.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-10
  • 2013-08-03
  • 1970-01-01
  • 2023-03-27
  • 2013-05-20
  • 2011-04-27
相关资源
最近更新 更多