views:

61

answers:

2

I'm trying to bind a list box in the simplest manner possible with the goal of understanding binding a little better. All examples I see online show data template, and I don't want to get that complicated yet. I have a collection of objects. These objects have a property of string type, and that's what I want to show in the list box. Below is all the code. Nothing shows up when I run this. What am I missing?

// The simple object
public class GameData 
{
  public string Team { get; set; }
}

// Window1.xaml
<Grid>
  <ListBox ItemSource="{Binding GameCollection}" DisplayMemberPath="Team"></ListBox>
</Grid>

// Window1.xaml.cs file
public partial class Window1 : Window
{
  //public ObservableCollection<GameData> GameCollection;
  // Changed to property per SLaks idea but still no luck
  public ObservableCollection<GameData> GameCollection
  {
    get;
    set;
  }


  public Window1()
  {
    GameCollection = new ObservableCollection<GameData>();
    GameCollection.Add("Tigers");
    GameCollection.Add("Indians");
    GameCollection.Add("Royals");

    InitializeComponent();
  }
}
+3  A: 

Remove your GameCollection field and set the Window's DataContext instead.

You can then bind directly to the DataContext using {Binding}.

SLaks
Still no luck after changing it to a property.
bsh152s
@bsh152s: He is saying to write something similar to `this.DataContext = GameCollection`.
Merlyn Morgan-Graham
+2  A: 

Here's some changes I made to get it to work:

// The simple object
public class GameData
{
    public string Team { get; set; }
}

public partial class Window1 : Window
{
    public ObservableCollection<GameData> GameCollection { get; set; }

    public Window1()
    {
        this.DataContext = this;
        GameCollection = new ObservableCollection<GameData>();
        GameCollection.Add(new GameData(){Team = "Tigers"});
        GameCollection.Add(new GameData(){Team = "Royals" });
        GameCollection.Add(new GameData(){Team = "Indians" });

        InitializeComponent();
    }
}


<Grid>
    <ListBox ItemsSource="{Binding GameCollection}" DisplayMemberPath="Team"/>
</Grid>
Chris Persichetti
Thanks, that did the trick. I was trying to do everything in xaml and I assumed the DataContext would default to "this". I guess I was wrong.
bsh152s