简体   繁体   中英

Can't bind properly DataGrid and ObservableCollection

Just started working with WPF and I am trying to work with the data grid and ObservableCollection with binding the data between them and I got a few questions about that subject:

  1. I did a binding to the ItemsSource on the XAML file to the cs ObservableCollection property and when I did it through the XAML I didn't see any data displayed in the DataGrid but when I did this:

    mainWindow_myDataGrid.ItemsSource = dbData

(mainWindow_myDataGrid is the XAML DataGrid , dbData is ObservableCollection property) it worked and I don't have a clue why.

  1. When I did the binding through the code (mainWindow_myDataGrid.ItemsSource = dbData) . I didn't use the DataGridTextColumn view in the XAML file and I saw the data in it. But when I did used it, it crashed with an error that says

"error when adding a row",

then again I have no clue why.

I firstly tried to find answers on my self of course with no success. If anyone could clear those points to me that would be great!

if you have code like this: mainWindow_myDataGrid.ItemsSource = dbData then you do NOT any kind of binding. you simply set the itemssource. you dont post enough code but i will give you an example

when you wanna use binding you need a public property

  public OberservableCollection<YourDataType> MyCollection {get;set;}

fill your collection and set the DataContext to the object(viewmodel) with your Collection. create your Binding in XAML

 <DataGrid ItemsSource="{Binding MyCollection}" />

thats all.

if this dont work then most time the DataContext is not right or the Binding Expression is wrong. you can check this at runtime with Snoop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM