0

我通过 Blend 2017 (.net 4.7) 创建了一个新的 WPF 项目,带有一个窗口和这个 Xaml(后面没有添加任何代码):

<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>

它编译但报告有关行的运行时错误

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

异常: 导致异常System.Windows.Markup.XamlParseException:的值。System.Windows.Markup.StaticResourceHolder

InnerException:System.Windows.Controls.Border找不到资源。

设计师足够聪明,可以展示正确的东西:带子绑定的边框

4

1 回答 1

0

我们可以通过省略边框样式的x:Keyand属性来解决这个问题:BasedOn

<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>
于 2017-06-10T10:10:36.330 回答