tags:

views:

112

answers:

1

I have a DockPanel with "StackPanel rows".

I need each StackPanel row to get the same style, however, the FIRST StackPanel row which should get one addition style.

In CSS I would do this using the cascading feature which I don't seem to have in XAML styles. Is it possible then to have multiple styles as shown in the pseudo code below? How is this common issue solved in XAML styles?

<Window x:Class="TestBinding99382.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestBinding99382"
    Title="Window1" Height="300" Width="300">

    <Window.Resources>
        <ObjectDataProvider x:Key="DataSourceCustomer" ObjectType="{x:Type local:Customer}" MethodName="GetCustomer"/>

        <Style x:Key="DataRowStyleFirst" TargetType="StackPanel">
            <Setter Property="Margin" Value="0 20 0 0"/>
        </Style>

        <Style x:Key="DataRowStyle" TargetType="StackPanel">
            <Setter Property="Orientation" Value="Horizontal"/>
            <Setter Property="VerticalAlignment" Value="Top"/>
            <Setter Property="Margin" Value="0 0 0 0"/>
            <Setter Property="DataContext" Value="{StaticResource DataSourceCustomer}"/>
            <Setter Property="DockPanel.Dock" Value="Top"/>
        </Style>

    </Window.Resources>

    <DockPanel>

        <!-- PSEUDO CODE -->
        <StackPanel Style="{StaticResource DataRowStyle,DataRowStyleFirst}">
            <TextBlock Text="First Name:"/>
            <TextBox Text="{Binding Path=FirstName}" Width="200" Margin="3 0 0 0"/>
        </StackPanel>

        <StackPanel Style="{StaticResource DataRowStyle}">
            <TextBlock Text="Last Name:"/>
            <TextBox Text="{Binding Path=LastName}" Width="200" Margin="3 0 0 0"/>
        </StackPanel>

    </DockPanel>
</Window>
+3  A: 

There is a style "BasedOn" property which allows simple inheritance of style values.

    <Style x:Key="DataRowStyleFirst" TargetType="StackPanel" BasedOn="{StaticResource DataRowStyle}">
        <Setter Property="Margin" Value="0 20 0 0"/>
    </Style>

...

    <StackPanel Style="{StaticResource DataRowStyleFirst}">
        <TextBlock Text="First Name:"/>
        <TextBox Text="{Binding Path=FirstName}" Width="200" Margin="3 0 0 0"/>
    </StackPanel>

    <StackPanel Style="{StaticResource DataRowStyle}">
        <TextBlock Text="Last Name:"/>
        <TextBox Text="{Binding Path=LastName}" Width="200" Margin="3 0 0 0"/>
    </StackPanel>
Martin Harris
Perfect, thanks!
Edward Tanguay