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 Wind开发者_如何学Pythonow1 : 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();
}
}
Remove your GameCollection
field and set the Window
's DataContext
instead.
You can then bind directly to the DataContext using {Binding}
.
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>
精彩评论