Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF XAML - Adding multiple styles to resource dictionary which target rowdefinition

Thanks for your thoughts in helping a relative beginner understand WPF.

I am trying to use the following style template in an XAML file for a WPF application:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary>
                    <Style TargetType="{x:Type RowDefinition}"
                        x:Key="hideIfNotDischarged">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding DischargedBy28Days,
                                Mode=OneWay}" Value="false">
                                <Setter Property="Height" Value="0" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                    <Style TargetType="{x:Type RowDefinition}"
                        x:Key="hideIfOutcomeKnownAndAlive">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsKnownDead,
                                Mode=OneWay}" Value="false">
                                <Setter Property="Height" Value="0" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

Which will be later used in a grid like so:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="30" />
        <RowDefinition Style="{StaticResource hideIfNotDischarged}" />
        ...

However, if there is more than 1 style element targeting Type RowDefinition AND ALSO the ResourceDictionary is nested within a MergedDictionary (even with only a single child ResourceDictionary to merge) the application fails with System.Windows.ResourceDictionary.DeferrableContent: Item has already been added.

That is, despite the fact the 2 styles have different keys, the resource dictionary is trying to add a dictionary item with name based purely on the target type (and ignoring the key).

Any help with how I might overcome this would be most appreciated.

like image 394
Brent Avatar asked Oct 17 '13 00:10

Brent


1 Answers

Xaml is parsed left to right so I think its checking the ResourceDictionary or the other MergedDictionaries if the TargetType (default identifier if no x:Key is used) exists before it realizes it has an x:Key identifier

Try setting the x:Key before the TargetType.

this could be a bug in the Xaml parser or it could be by design, It may be worth a look on Microsoft Connect

like image 178
sa_ddam213 Avatar answered Nov 15 '22 11:11

sa_ddam213