TheHvidsten
TheHvidsten

Reputation: 4428

Can't use resources defined in Window.Resources

I have a WPF project with a Window. I've added a style to the resources for that window and I'm trying to use that style on a component, but the resource can't be found!

I believe the syntax is as basic as it can be, and also the same as numerous examples I've seen online:

<Window x:Class="MyView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <Style x:Name="ComponentsListItem" TargetType="{x:Type ListViewItem}">
            <!-- Some styles -->            
        </Style>
    </Window.Resources>
    <Grid>
        <ListView ItemContainerStyle="{StaticResource ComponentsListItem}" />
    </Grid>
</Window>

When I'm compiling I get an error on {StaticResource ComponentsListItem} that says

The resource "ComponentsListItem" could not be resolved

I have also tried putting the style into a <ResourceDictionary> so that it looks like this:

<Window.Resources>
    <ResourceDictionary>
        <Style x:Name="ComponentsListItem" TargetType="{x:Type ListViewItem}">
            <!-- Some styles -->            
        </Style>
    </ResourceDictionary>
</Window.Resources>

But that gives exactly the same error message on the exact same place.

What is going on here? Why can't I use ComponentsListItem?

Upvotes: 0

Views: 80

Answers (1)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Why can't I use ComponentsListItem

That's because you are using x:Name but styles are defined by using x:Key.

Use this and it will work fine

<Style x:Key="ComponentsListItem" TargetType="{x:Type ListViewItem}">
    <!-- Some styles -->            
</Style>

Upvotes: 4

Related Questions