WPF doesn't apply style to first element

邮差的信 提交于 2019-11-30 06:01:37

I've seen this problem a couple of times before and it's a pretty weird "bug". It happends when you put a Style directly in a ResourceDictionary inside <ResourceDictionary.MergedDictionaries>. The Style is skipped for the first item. This code produces the same result, the Style is skipped for the first ListBoxItem

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Foreground" Value="Green"/>
                </Style>
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>
<ListBox>
    <ListBoxItem Content="Item 1"/>
    <ListBoxItem Content="Item 2"/>
    <ListBoxItem Content="Item 3"/>
</ListBox>

To get both the styles and MergedDictionaries to work, do it like this instead

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/AllResources.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <Style TargetType="{x:Type Button}">
            <Setter Property="FontSize" Value="100"/>
        </Style>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Button Grid.Column="0" Content="1" Name="Button1"/>
    <Button Grid.Column="1" Content="2" Name="Button2"/>
</Grid>

Although it does not produce an error, according to the documentation:

a dictionary used in merged dictionaries should not have content and should use the Source property to refer to another dictionary indirectly. In fact if you put the Style in a resource dictionary and reference both of them in the merge, it works as it should.

We can only speculate why this is not supported but since it isn't, and since the workaround is easy, we can't complain too bitterly except to wish that we received an error at compile time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!