2

Why ist this Style not working in WPF? The TextBlock should be red, but it is not. It stays black. This is just happing when the TextBlock is in a Template.

<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>
pinki
  • 920
  • 1
  • 9
  • 8

2 Answers2

8

Implicit Styles in templates are limited to controls that inherit from System.Windows.Controls.Control unless they are defined in Application.Resources so either give your style x:Key and use it explicitly:

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

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

or move it to Application.Resources

<Application.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Red"></Setter>
    </Style>
</Application.Resources>
dkozl
  • 32,814
  • 8
  • 87
  • 89
-1

If you want to define a style and have it automatically apply to all controls of that type (without manually specifying the style for each control) you need to define it like this instead.

E.G.

<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>
kenjara
  • 402
  • 10
  • 18