在我的 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}"
添加到我的应用程序上的所有文本框。我想避免这样做。
最佳答案
您可以像这样不使用 x:Key 的“BasedOn”样式
<TextBox Text="Some Text" >
<TextBox.Style>
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Opacity" Value=".8" />
</Style>
</TextBox.Style>
</TextBox>
关于WPF创建样式而不覆盖默认样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32357973/