-1

I want to show a list box with an image and a string as list box items. To do so I bind a list of ThemeLayer as ItemsSource and defined an ItemTemplate.

XAML

<ListBox x:Name="DataLayerList" SelectionMode="Extended"
         ItemsSource="{Binding LayersFiltered, Mode=OneWay}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Path=ImagePath}" Height="16"/>
                <TextBlock Text="{Binding Path=Name}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ThemeLayer are defined as such:

C#

public class ThemeLayer
{
    public readonly string Name;
    public readonly string Id;
    public readonly string Type;
    public readonly string ImagePath;
    
    public override string ToString()
    {
        return Name;
    }

    public ThemeLayer(string name, string id, string type, string image)
    {
        Name = name;
        Id = id;
        Type = type;
        ImagePath = image;
    }
}

and the list LayersFiltered contains object of ThemeLayer similar to this:

 new ThemeLayer("Place","eb760ca1bb494d2887c5d8c51ccc417a", "image", "ImageLayer16.png")

When I run my project then I am getting the list box filled with items, but I cannot see a single one. I only know because hovering over the list reveals the different lines of the list box items.

Looking at XAML Binding Failures I get back that ImagePath and Name (defined in the ItemTemplate) cannot be found on object of type ThemeLayer, even though the objects in LayersFiltered certainly are of type ThemeLayer and each of them has a property Name and ImagePath.

The ThemeLayer class and the class defining the list of ThemeLayer are both in my Models folder, and LayersFiltered is a list object within my ViewModel.

How do I have to define the XAML that I get images and names shown?

One more thing:

The images to be shown in the list box are situated within the project, at a folder Images. Is it okay to simply reference the image by its name, as shown above, or does that need to be something along the line of "/Images/filename.png"?

TomGeo
  • 1,213
  • 2
  • 12
  • 24

1 Answers1

1

You need to bind to properties rather than fields. Change this...

public readonly string Name;
public readonly string Id;
public readonly string Type;
public readonly string ImagePath;

to be

public string Name { get; }
public string Id { get; }
public string Type { get; }
public string ImagePath { get; }

These properties are read only, just like the fields they replace.

Richardissimo
  • 5,596
  • 2
  • 18
  • 36