i've been researching on how to Bind a GridView to a ObservableCollection. All the examples do the same steps, but it doesn't work on my application.
I have even copied the example here: http://www.switchonthecode.com/tutorials/wpf-tutorial-using-the-listview-part-1
The DisplayMemberBinding is working when declare the items in XAML so the problem must be the c开发者_运维问答ollection.
For 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>
For the 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; }
}
Your binding won't be finding the property on your form. You're not specifying where to find GameCollection
: the binding doesn't know where to look.
Add a x:Name="someName"
to the root element of your Window, and then modify the binding to be {Binding GameCollection, ElementName=someName}
. That'll fix the problem with the binding.
actually all u need to do is make sure the datacontext is set properly
DataContext="{Binding RelativeSource={RelativeSource Self}}" put that in the tag for the window.
精彩评论