none
Binding ObservableCollection to a Datagrid (very little code)

    Question






  • <UserControl x:Class="TestDataGrid"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                 mc:Ignorable="d"
                 d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
            <DataGrid Name="dg" />
        </Grid>
    </UserControl>
    ---------------------------------------------------------
    Imports System.Collections.ObjectModel

    Public Class TestDataGrid
        Public Sub DataCollection(ByVal _files As ObservableCollection(Of DataProperty))
            'Me.DataContext = _files
            dg.ItemsSource = _files
            dg.DataContext = _files


        End Sub
    End Class


    From what I understand the datagrid should autogenerate columns and populate the grid just from what I have above. However on my mainwindow the usercontrol remains blank even though the the item source has the data. I know I should be able to set the datacontext in the code behind and then in the XAML set the ItemSource={Binding} but that does not seem to work either and I was just checking to see that the item source was being populated.

    Friday, May 27, 2011 11:48 AM

Answers

  • Thank you for your quick replies. Someone smarter than I pointed out what you all are saying and that is I was creating a new usercontrol object with my code that was caling my sub in the usercontrol. So the mainwindow was bringing up my TestDataGrid user control just like it was supposed to, just new the new one I created.

     

    I did try and delete this but I guess once there is a reply you can't.

    Friday, May 27, 2011 12:47 PM

All replies

  • Hello Tycho, remember that your DataProperty class need to have the members you need to show defined as Properties not as Fields. Can you paste the definition of your DataProperty class?

    Regards,

    Miguel.

    Friday, May 27, 2011 11:58 AM
  • I think Miguel is likely correct and the code you have not shown us is the problem.

    My VB is a bit rusty.

    You're passing into the constructor by value rather than reference?

    Friday, May 27, 2011 12:34 PM
  • Your TestDataGrid is a copy and not a reference to the one on the GUI.  :)
    Friday, May 27, 2011 12:39 PM
  • Thank you for your quick replies. Someone smarter than I pointed out what you all are saying and that is I was creating a new usercontrol object with my code that was caling my sub in the usercontrol. So the mainwindow was bringing up my TestDataGrid user control just like it was supposed to, just new the new one I created.

     

    I did try and delete this but I guess once there is a reply you can't.

    Friday, May 27, 2011 12:47 PM