在我的WPF应用程序中,我想要为所有的文本框设置样式。因此,我的App.xaml文件如下:
<Application x:Class="IM.WindowsApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="Yellow"/>
</Style>
</Application.Resources>
</Application>
在 MainWindow.xaml 文件中,我有以下内容:
<TextBox Text="Some Text" />
当我运行它时,文本显示为黄色,就像我预期的那样。
现在我的问题是,我想在文本框中添加一些额外的样式。因此,我修改了代码如下:
<TextBox Text="Some Text">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Opacity" Value=".8" />
</Style>
</TextBox.Style>
</TextBox>
当我运行代码后,文本框的前景色不再是黄色 :( 。我不想更改样式。
一个解决方案是给原始样式一个资源键。然后我可以使用
BasedOn={StaticRecource MyResourceKey}
。但这不是一个好的解决方案,因为我必须在应用程序中的所有文本框中添加 Style="{StaticResource MyResourceKey}"
。我希望避免这样做。
<Style TargetType="{x:Type Control}" x:Key="TxtInputBase" ... etc
然后创建了<Style TargetType="{x:Type PasswordBox}" BasedOn="{StaticResource TxtInputBase}" />
这样做使你的技术起作用了。非常感谢!我不明白为什么。也许我必须清理解决方案,这没有意义。无论如何,再次感谢帮助,效果很好。 - Tono Nam