1

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 collection.

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; }
}

2 Answers 2

2

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.

3
  • Actually, there is a Property called GameCollection further down so only the ElementName part applies Feb 15, 2011 at 16:53
  • Sorry! Failure to scroll, I guess :-) Editing!
    – Dan Puzey
    Feb 15, 2011 at 17:03
  • Yes, it was the name problem, it's working perfectly now, Thanks!
    – Caian
    Feb 15, 2011 at 17:17
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.