【问题标题】:Global Style not working in WPF [duplicate]全局样式在 WPF 中不起作用 [重复]
【发布时间】:2014-03-27 15:46:55
【问题描述】:

为什么这种样式在 WPF 中不起作用? TextBlock 应该是红色的,但不是。它保持黑色。这只是在 TextBlock 位于模板中时发生。

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Red"></Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <ListView>
            <ListView.Items>
                <ListItem></ListItem>
            </ListView.Items>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock>Hallo</TextBlock>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

    </Grid>
</Window>

【问题讨论】:

标签: c# wpf


【解决方案1】:

模板中的隐式Styles 仅限于从System.Windows.Controls.Control 继承的控件,除非它们在Application.Resources 中定义,因此请提供您的样式x:Key 并明确使用它:

<Window.Resources>
    <Style TargetType="TextBlock" x:Key="myTextBlockStyle">
        <Setter Property="Foreground" Value="Red"></Setter>
    </Style>
</Window.Resources>

<TextBlock Style="{StaticResource myTextBlockStyle}">Hallo</TextBlock>

或将其移至Application.Resources

<Application.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Red"></Setter>
    </Style>
</Application.Resources>

【讨论】:

    【解决方案2】:

    如果您想定义一个样式并让它自动应用于该类型的所有控件(无需手动指定每个控件的样式),您需要改为这样定义它。

    例如

    <Style x:Key="{x:Type TextBox}" TargetType="TextBox">
            <Setter Property="IsUndoEnabled" Value="True"></Setter>
            <Setter Property="UndoLimit" Value="10"></Setter>
            <Setter Property="ContextMenu" Value="{StaticResource textContextMenu}"></Setter>
            <Setter Property="SpellCheck.IsEnabled" Value="True"></Setter>
        </Style>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-06
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多