WPF创建样式而不覆盖默认样式

标签 wpf xaml styles resourcedictionary

在我的 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/

相关文章:

WPF 在 CompositeCollection 中绑定(bind) MenuItem 不起作用

c# - 使用比例网格大小时(*)如何自动限制行/列的最小尺寸?

WPF 设计问题(自定义控件或 mvvm)

c# - WPF DataGrid : How do I access the DataRow a TextBox etc. 驻留在?

XAML WebView 绑定(bind)到 HTML 源不起作用

WPF TreeView 悬停时突出显示行

c# - 为什么我不能在 XAML 中定义带有转换的几何图形?

c# - 没有为控件模板中的数据网格设置依赖属性

WPF TreeView : How to style selected items with rounded corners like in Explorer

javascript - 在 StyleSheet 中使用函数是否存在性能缺陷?