Silny ToJa
Silny ToJa

Reputation: 2261

Why Window.Resources is used for controls in reference library?

I have two project first is library and have UserControl.

<UserControl x:Class="TestControl.TextTest"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:TestControl"
         mc:Ignorable="d" 
         d:DesignHeight="150" d:DesignWidth="300">
    <Grid Background="White">
         <TextBlock Text="Test" FontSize="100"/>
    </Grid>
</UserControl>

Second project have Window with define Window.Resources and use control from library

<Window x:Class="WpfTestApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfTestApp2"
    xmlns:TestControl="clr-namespace:TestControl;assembly=TestControl"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800" KeyDown="Window_KeyDown">
    <Window.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Background" Value="#6b5656"/>
        </Style>
    </Window.Resources>
    <Grid>
         <TestControl:TextTest/>
    </Grid>
</Window>

Why TextBlock from Library have background color from WindowS.Resources in other project?

is it possible to block this behavior?

Upvotes: 0

Views: 58

Answers (2)

Standard_101
Standard_101

Reputation: 325

Since you don't have a x:key in your <Style></Style> section, the resource style is applied by default to all the applicable contents in the window.

Yes, it's possible to block this behavior. Just add a x:key and use the key wherever you want the style to be applied.

Upvotes: 1

Rekshino
Rekshino

Reputation: 7325

This is because you use implicit style for all TextBlock elements:

<Style TargetType="{x:Type TextBlock}">
   <Setter Property="Background" Value="#6b5656"/>
</Style>

To suppress it you can also specify implicit or explicit style in the UserCotrol or you can set the Style or property directly by the control.
If you want to have a background color from Grid:

<TextBlock Text="Test" FontSize="100" Background="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=Background}"/>

Upvotes: 1

Related Questions