wpf datagrid databind with nested objects (like master detail)
Asked Answered
C

1

6

I have a simple problem binding an entity to datagrid in wpf.

I have an entity Called "User".... and each "User" have one "Workgroup" .. the relationship between the two is one to one.

now in EF every User entity has one workgroup entity inside.

when I want to bind Users Collection to datagrid I have no clue hot to say that you have to put forexample workgroup.Title inside a datagrid Column

I'm trying to bind in this way :

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Users}" HorizontalAlignment="Stretch" Margin="5" Name="dgUserList" VerticalAlignment="Stretch" SelectionChanged="dgUserList_SelectionChanged">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding FirstName}" Header="FirstName" />
                    <DataGridTextColumn Binding="{Binding LastName}" Header="LastName" />
                    <DataGridTextColumn Binding="{Binding Username}" Header="UserName" />
                    <DataGridTextColumn Binding="{Binding WorkGroup}" Header="Workgroup" />
                </DataGrid.Columns>
            </DataGrid>

Code Behind : Created a property like this :

public List<User> Users
    {
        get { return dal.GetUsers(); }
    }

and do the binding :

private void BindGrid()
    {
        dgUserList.ItemsSource = Users;
    }

this work file with direct properties of User Entity but it puts type of Workgroup entity inside the datagrid column and the reason is obvious. I want to put the Title of workgroup inside

how can i achive this ?

any help would be greatly appreciated

Clang answered 12/7, 2011 at 20:23 Comment(0)
P
8

WPF Bindings support nested properties so to get to any of the sub-properties on a property of a bound object just use normal "." syntax:

<DataGridTextColumn Binding="{Binding WorkGroup.Title}" Header="Workgroup" />

You also don't need to set the ItemsSource twice. If you have the DataContext of the DataGrid set up as the Window (or UserControl, etc.) whose code-behind declared the Users property then the ItemsSource Binding in XAML is sufficient and you can remove the BindGrid method. If you haven't set the DataContext, the XAML ItemsSource Binding isn't doing anything (you can probably see an error message in your Debug Output) so you can remove that and just let the code-behind method take care of it.

You should also consider using an ObservableCollection to get automatic notification and UI updates when items are added or removed. Since you're already using EF you may also be able to just use the EntityCollection for User, which includes the same automatic INotifyCollectionChanged notification.

Presnell answered 13/7, 2011 at 0:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.