I have run across a problem when overriding default styles in an MVVM . I am trying to change the default foreground value of all of the text in my application. This works until I have Text Blocks in UserControls. These Text Blocks do not inherit from the default, unlike the other controls such as Labels.
I have created a small example for this.
I have a generic Resource dictionary declared. This is holding the default styles.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1.Resources">
<Style TargetType="Label">
<Setter Property="Foreground"
Value="Blue" />
</Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground"
Value="Red" />
</Style>
This resource dictionary is merged into the MainWindow.
<Window>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
<DataTemplate DataType="{x:Type vm:UserControlViewModel}">
<v:UserControl1 />
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Grid>
<Label>Main Window Label</Label>
<TextBlock Grid.Column="1">Main Window Text Block</TextBlock>
<ContentPresenter Content="{Binding Content}" />
</Grid>
</Window>
In my simple example I have a generic MainViewModel set to the DataContext of the MainWindow.
public class MainViewModel
{
public UserControlViewModel Content { get; set; }
public MainViewModel()
{
Content = new UserControlViewModel();
}
}
The user control viewmodel is simply a shell with no properties that need to be displayed. However the user control itself is just a simple label and text block like the Main Window
<UserControl>
<Grid>
<Label>UserControl Label</Label>
<TextBlock >User Control Text Block</TextBlock>
</Grid>
</UserControl>
The weird part is the override for the Label works properly and the Text Block does not. This is the picture of the end result.
Why does the Text Block in the user control not use the default style that is applied to the Text Block?