"文本控件占位符前景"资源如何不适用于文本框



我开始学习通用Windows应用程序。对于我的演示应用程序,我正在尝试更改TextBox控件的占位符前台。为了设置它的颜色,我在包含控件的同一XAML页面定义上设置了一个名为TextControlPlaceholderForeground的资源键(根据本文档(。但是,未设置TextBox的占位符颜色。当控件未处于焦点状态时,看起来好像没有设置占位符文本。当它接收到焦点时,占位符变为可见,但仍然不是为其设置的颜色

<Page
x:Class="MyApp.AuthenticationPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<SolidColorBrush x:Key="TextControlPlaceholderForeground" Color="Green" />
</Page.Resources>
<Grid>
<Border
HorizontalAlignment="Center"
VerticalAlignment="Bottom"
Margin="0,0,0,10"
Background="White"
Padding="10"
CornerRadius="10"
Width="300"
>
<StackPanel Orientation="Vertical">
<!-- The placeholder of the TextBox below doesn't become green -->
<TextBox x:Name="emailInput" PlaceholderText="Email" Margin="0,0,0,10" />

<!-- However, the placeholder of this PasswordBox becomes green -->
<PasswordBox x:Name="passwordInput" PlaceholderText="Password" Margin="0,0,0,10" />
<Button HorizontalAlignment="Stretch" Content="LOG IN" Click="onLoginSubmit" Style="{StaticResource AccentButtonStyle}"/>
<HyperlinkButton FontSize="11" Foreground="Black" Content="Forgot your password?" HorizontalAlignment="Center" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<TextBlock Text="Don't have an account yet?" Foreground="Black" FontSize="11" Padding="0,0,5,0"/>
<HyperlinkButton Padding="0" FontWeight="Normal" >
<TextBlock Text="Create new account" Foreground="Black" TextDecorations="Underline" FontSize="11"/>
</HyperlinkButton>
</StackPanel>
</StackPanel>
</Border>
</Grid>
</Page>

观察:当我尝试通过Style标签设置TextBox的占位符文本颜色时,它是有效的。

<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Setter Property="PlaceholderForeground" Value="Green" />
</Style>

我不明白这里发生了什么。我知道我错过了一些很小的东西,但看不见。

首先,让我解释为什么第二种方法有效。PasswordBoxTextBox在如何定义占位符文本颜色方面有一点不同。PasswordBoxTextBox的样式中都有一个PlaceholderTextContentPresenter元素,即TextBlock。但当使用此TextBlock时,它们对于Foreground属性具有不同的值。

文本框:

<TextBlock x:Name="PlaceholderTextContentPresenter" Foreground="{Binding PlaceholderForeground, RelativeSource={RelativeSource Mode=TemplatedParent}, TargetNullValue={ThemeResource TextControlPlaceholderForeground}}" 

密码框

<TextBlock x:Name="PlaceholderTextContentPresenter" Foreground="{ThemeResource TextControlPlaceholderForeground}"

您可以看到PasswordBox直接使用您定义为颜色的TextControlPlaceholderForeground,但TextBoxextBox将根据您的需要显示颜色。

因此,回到第一个问题,如果您想更改占位符文本的前景,则需要创建TextBox的默认样式,并更改PlaceholderTextContentPresenter元素的前景绑定,以便像**PasswordBox**那样直接使用TextControlPlaceholderForeground

最新更新