我正在尝试以最简单的方式绑定列表框,目的是更好地理解绑定。我在网上看到的所有例子都显示了数据模板,我不想让它复杂化。我有一组对象。这些对象具有字符串类型的属性,这就是我想在列表框中显示的内容。以下是所有代码。运行时没有任何东西出现。我错过了什么?
// 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();
}
}
答案 0 :(得分:3)
删除您的GameCollection
字段,然后设置Window
的{{1}}。
然后,您可以使用DataContext
直接绑定到DataContext。
答案 1 :(得分:2)
以下是我为使其发挥作用而做出的一些改变:
// 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>