taralex
taralex

Reputation: 935

Bind datagrid to a collection of objects in Silverlight

I know I did it and it worked. Now I'm doing the same thing and it doesn't. What am I missing? I created a new test solution and added the following code:

XAML:

 <Grid x:Name="LayoutRoot" Background="White">
        <data:DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="98,31,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200">
            <data:DataGrid.Columns>
                <data:DataGridTextColumn Binding="{Binding TestProperty}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" x:Name="d" />
            </data:DataGrid.Columns>
        </data:DataGrid>
    </Grid>

C#:

namespace SilverlightApplication1
    {
        public partial class MainPage : UserControl
        {
            public MainPage()
            {
                InitializeComponent();            
                dataGrid1.ItemsSource = null;
                List<TestClass> lst = new List<TestClass>();
                TestClass tc = new TestClass();
                tc.TestProperty = "HEllo";
                lst.Add(tc);
                dataGrid1.ItemsSource = lst;
            }
        }
        class TestClass
        {
            public String TestProperty { get; set; }
        }
    }

There's literally nothing more. I press F5 and see a grid with one column and one row (as expected), but the row is empty! And I expected "HEllo" there. I feel there's something basic, but can't figure out what. Drives me crazy the whole day today!

Upvotes: 0

Views: 3535

Answers (1)

slugster
slugster

Reputation: 49974

I would do two things here:

Make TestClass public (this will probably fix the problem):

public class TestClass
{
    public String TestProperty { get; set; }
}

Statically bind the datagrid:

public MainPage()
{
    InitializeComponent();   

    DataContext = this;         

    MyItems = ... create the list ...
}

public ObservableCollection<TestClass> MyItems { get; set; }



<Grid x:Name="LayoutRoot" Background="White">
    <data:DataGrid ItemsSource="{Binding MyItems}" ...etc... Name="dataGrid1">
        <data:DataGrid.Columns>
            <data:DataGridTextColumn Binding="{Binding TestProperty}" Width="Auto" x:Name="d" />
        </data:DataGrid.Columns>
    </data:DataGrid>
</Grid>

Upvotes: 1

Related Questions