Border style based on standard control causing runtime error

917 Views Asked by At

I created a new WPF project by Blend 2017 (.net 4.7) with one window and this Xaml (added no code behind):

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Window.Resources>
        <Style x:Key="_borderStyleWithChildBinding"
               TargetType="{x:Type Border}"
               BasedOn="{StaticResource {x:Type Border}}">
            <Setter Property="BorderBrush"
                    Value="{Binding RelativeSource={RelativeSource Self}, Path=Child.Fill}" />
        </Style>
    </Window.Resources>
    <Grid Width="50"
          Height="30"
          Margin="10">
        <Border BorderThickness="5"
                Style="{StaticResource _borderStyleWithChildBinding}">
            <Border.Child>
                <Rectangle Width="20"
                           Height="10"
                           Fill="Green" />
            </Border.Child>
        </Border>
    </Grid>
</Window>

It compiles but reports a runtime error concerning line

BasedOn="{StaticResource {x:Type Border}}"

Exception: System.Windows.Markup.XamlParseException: A value for System.Windows.Markup.StaticResourceHolder caused an exception.

InnerException: Resource System.Windows.Controls.Border cannot be found.

The designer is smart enough to show the right thing:Border with child binding

1

There are 1 best solutions below

0
Pollitzer On

We can solve the problem by omitting the x:Key and the BasedOn property of the border style:

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Window.Resources>
        <Style TargetType="{x:Type Border}" >
            <Setter Property="BorderBrush"
                    Value="{Binding RelativeSource={RelativeSource Self}, Path=Child.Fill}" />
        </Style>
    </Window.Resources>
    <Grid Width="50"
          Height="30"
          Margin="10">
        <Border BorderThickness="5">
            <Border.Child>
                <Rectangle Width="20"
                           Height="10"
                           Fill="Green" />
            </Border.Child>
        </Border>
    </Grid>
</Window>