2

I have basic problem with WPF, I tried setting DataContext, binding to collection and somehow I still cannot get it to work. I searched way to long for such basic problem... I must be missing something very simple. I appreciate any help :)

Code-behind:

public ObservableCollection<Photo> MyPhotos = new ObservableCollection<Photo>();
public DataTemplate()
{
  InitializeComponent();
  listBox.DataContext = MyPhotos;
  MyPhotos.Add(new Photo(@"path to existing file"));
}

XAML

<Window.Resources>
  <DataTemplate DataType="{x:Type local:Photo}">
    <Border Margin="3">
      <Image Source="{Binding Source}"/>
    </Border>
  </DataTemplate>
</Window.Resources>
<Grid>
  <ListBox Name="listBox" ItemsSource="{Binding MyPhotos}" Background="Silver" Width="600" Margin="10" SelectedIndex="0"/>
</Grid>

Photo class:

public class Photo
{
  public string Source { get; set; }
  public Photo(string path)
  {
    Source = path;
  }
}
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69

2 Answers2

4

You need to reference DataTemplate as ItemTemplate into your ListBox. Define Key into your DataTemplate.

<Window.Resources>
      <DataTemplate x:Key="MyItemTemplate" DataType="{x:Type local:Photo}">
        <Border Margin="3">
          <Image Source="{Binding Source}"/>
        </Border>
      </DataTemplate>
    </Window.Resources>

    <ListBox Name="listBox" ItemsSource="{Binding MyPhotos}" Background="Silver" Width="600" Margin="10" SelectedIndex="0" ItemTemplate="{StaticResource MyItemTemplate}"/>

UPDATE

Change your DataContext to this.

listBox.DataContext = this;
Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34
2
  1. MyPhotos have to be a Property {get; set} functions, NOT a Field

    public ObservableCollection<Photo> MyPhotos { get; set; }

  2. Code behind:

    DataContext = this

    NOT listBox.DataContext = MyPhotos

  3. XAML: Add DisplayMemberPath to show data

    DisplayMemberPath="Source"

thuc do van
  • 131
  • 1
  • 7