如何更改uwp输入控件描述的前景色



我在代码隐藏文件中验证文本框的输入,有时它涉及数据库的内容。

如果错误发生在验证阶段,我会将一些错误消息设置为文本框的描述。

我想做的是将描述的前景颜色和边框更改为红色。

我该怎么做?

当您使用TextBox时,它将使用默认模板,其样式如下:

<Style TargetType="TextBox">
..
<ContentPresenter x:Name="DescriptionPresenter" AutomationProperties.AccessibilityView="Raw" Content="{TemplateBinding Description}" Grid.ColumnSpan="2" Grid.Column="0" Foreground="{ThemeResource SystemControlDescriptionTextForegroundBrush}" Grid.Row="2" x:Load="False"/>
…
</Style>

如您所见,有一个名为DescriptionPresenter的ContentPresenter,它控制TextBox的Description属性。因此,您可以使用Visual Tree找到这个ContentPresenter并访问它,然后您可以更改它的前景。要更改TextBox的边框颜色,可以直接使用TextBox的BorderBrush属性。请参考以下代码。

private void Button_Click(object sender, RoutedEventArgs e)
{
var contentPresenter=FindChild<ContentPresenter>(myTextbox);         
contentPresenter.Foreground = new SolidColorBrush(Colors.Blue);
myTextbox.BorderBrush = new SolidColorBrush(Colors.Green);
}
public T FindChild<T>(DependencyObject parent)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T typedChild)
{
var name= child.GetValue(NameProperty);
if (name.ToString()== "DescriptionPresenter") 
{
return typedChild;
}  
}
var inner = FindChild<T>(child);
if (inner != null)
{
return inner;
}
}
return default;
}

最新更新