Ton*_*Nam 4 wpf xaml styles resourcedictionary
在我的wpf应用程序中,我想为所有TextBox设置样式。结果,我的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>
Run Code Online (Sandbox Code Playgroud)
在MainWindow.xaml中,我具有:
<TextBox Text="Some Text" />
Run Code Online (Sandbox Code Playgroud)
当我运行该程序时,它的文本显示为黄色,与我预期的一样。
现在这是我的问题
现在,我想向该文本框添加一些其他样式。结果,我将代码修改为如下所示
<TextBox Text="Some Text">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Opacity" Value=".8" />
</Style>
</TextBox.Style>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
当我运行时,我的文本框前景不再是黄色:(。我不想替换样式。
一种解决方案是为原始样式提供资源密钥。然后我可以放置BasedOn={StaticRecource MyResourceKey}。这不是解决方案,因为我必须Style="{StaticResource MyResourceKey}"在我的应用程序中添加到所有文本框。我想避免这样做。
小智 6
您可以在没有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>
Run Code Online (Sandbox Code Playgroud)