我一直在研究如何将GridView绑定到ObservableCollection。所有示例都执行相同的步骤,但它不适用于我的应用程序。
我甚至在这里复制了这个例子:http://www.switchonthecode.com/tutorials/wpf-tutorial-using-the-listview-part-1
在声明XAML中的项目时,DisplayMemberBinding正在工作,因此问题必须是集合。
对于XAML:
<ListView ItemsSource="{Binding GameCollection}" Margin="0,123,0,41">
<ListView.View>
<GridView>
<GridViewColumn Width="140" Header="Game Name"
DisplayMemberBinding="{Binding GameName}" />
<GridViewColumn Width="140" Header="Creator"
DisplayMemberBinding="{Binding Creator}" />
<GridViewColumn Width="140" Header="Publisher"
DisplayMemberBinding="{Binding Publisher}" />
</GridView>
</ListView.View>
</ListView>
对于CS
public partial class MainWindow : Window
{
ObservableCollection<GameData> _GameCollection =
new ObservableCollection<GameData>();
public MainWindow()
{
_GameCollection.Add(new GameData
{
GameName = "World Of Warcraft",
Creator = "Blizzard",
Publisher = "Blizzard"
});
_GameCollection.Add(new GameData
{
GameName = "Halo",
Creator = "Bungie",
Publisher = "Microsoft"
});
_GameCollection.Add(new GameData
{
GameName = "Gears Of War",
Creator = "Epic",
Publisher = "Microsoft"
});
InitializeComponent();
Focus();
}
public ObservableCollection<GameData> GameCollection
{ get { return _GameCollection; } }
}
public class GameData
{
public string GameName { get; set; }
public string Creator { get; set; }
public string Publisher { get; set; }
}
答案 0 :(得分:2)
您的绑定不会在您的表单上找到该属性。您没有指定查找GameCollection
的位置:绑定不知道在哪里查找。
将x:Name="someName"
添加到窗口的根元素,然后将绑定修改为{Binding GameCollection, ElementName=someName}
。这将解决绑定问题。
答案 1 :(得分:1)
实际上你需要做的就是确保正确设置datacontext
DataContext =“{Binding RelativeSource = {RelativeSource Self}}”将其放入窗口的标记中。