Wpf datagrid databind with nested objects (e.g. main part)

I have a simple problem connecting an entity with a datagrid in wpf.

I have an object called "User" .... and each "User" has one "Workgroup" .. the relationship between them is one to one.

Now in EF, each user object has within it one object of the workgroup.

when I want to bind a user collection to a datagrid, I don't have a hint to say that you need to put forexample workgroup.Title inside the datagrid column

I am trying to link 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: Created a property similar to this:

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

and bind:

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

this work file with direct User Entity properties, but it puts the type of the Workgroup object inside the datagrid column, and the reason is obvious. I want to put the name of the working group inside

how can i achieve this

any help would be greatly appreciated

+6
source share
1 answer

WPF bindings support nested properties, so simply use the usual "." To access any of the sub-properties of the properties of the associated object. Syntax:

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

You also do not need to set ItemsSource twice. If you have a DataContext from a DataGrid configured as a Window (or UserControl, etc.) whose code is declared as a Users property, then binding the ItemsSource in XAML is sufficient and you can remove the BindGrid method. If you did not set the DataContext, binding the XAML ItemsSource elements does nothing (you may see an error message on your debug output) so you can remove it and just let this method take care of it.

You should also consider using an ObservableCollection to receive automatic notifications and user interface updates when you add or remove items. Since you are already using EF, you can also just use EntityCollection for a user that includes the same automatic notification INotifyCollectionChanged.

+8
source

Source: https://habr.com/ru/post/892612/


All Articles