日期:2014-05-17  浏览次数:20760 次

|ZYCWPF| WPF如何写样式,只对当前控件的直接子节点有效的样式呢?谢谢 有示例XAML

<Window x:Class="_0_0_样式示例.Grid下统一指定控件样式"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Grid下统一指定控件样式" Height="300" Width="600">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.Resources>
            <Style TargetType="StackPanel"><!--我这里只想这个样式对当前Grid的直接子节点有效,子节点的子节点不管-->
                <Setter Property="Margin" Value="5 5 5 5"/>
            </Style>
        </Grid.Resources>
        <StackPanel Background="LightBlue" Grid.Row="0" Grid.Column="0">
            <StackPanel Background="AntiqueWhite">
                <TextBlock Text="我是在StackPanel里面的StackPanel,并不是在Gird的下级的,所以不相继承到Margin的设置" TextWrapping="Wrap"></TextBlock>
            </StackPanel>
        </StackPanel>
        <StackPanel Background="Aqua" Grid.Row="0" Grid.Column="1">
        </StackPanel>
        <StackPanel Background="Red" Grid.Row="1" Grid.Column="0">
        </StackPanel>
        <StackPanel Background="Yellow" Grid.Row="1" Grid.Column="1">
        </StackPanel>
    </Grid>
</Window>

如上面定义的Margin对Grid下的所有StackPanel都起了效果,
但我想写的样式为:样式对当前Grid的直接子节点有效,子节点的子节点无效
谢谢
------最佳解决方案--------------------

    <Grid.Resources>
        <Style TargetType="StackPanel">
            <!--我这里只想这个样式对当前Grid的直接子节点有效,子节点的子节点不管-->
            <Setter Property="Margin" Value="5 5 5 5"/>
            <Style.Resources>
 &nbs