Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to bind a datagrid to a list of objects and make it so that when I update an object in the list the change is reflected directly into the datagrid without needing to call a refresh.

My code is:

VB
Public Class BindingToAListOfObjectsUpdateable
    Private src As List(Of MyEFEntity)

    Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim db As New DbEntities
        src = db.MyEFEntity.ToList()
        dg.DataContext = src
        dg.ItemsSource = src
        db.Dispose()

    End Sub

    Private Sub Grid_Loaded(sender As Object, e As RoutedEventArgs)
        Me.WindowState = Windows.WindowState.Maximized

    End Sub

    Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
        MsgBox(src(0).Field1)
        src(0).Field1 = "EDITED"

    End Sub

    Private Sub Button_Click_2(sender As Object, e As RoutedEventArgs)
        dg.Items.Refresh()

    End Sub
End Class



XAML:
XML
<Window x:Class="BindingToAListOfObjectsUpdateable"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="BindingToAListOfObjectsUpdateable" Height="300" Width="300">
    <Grid Loaded="Grid_Loaded">
        <DataGrid x:Name="dg" AutoGenerateColumns="True" Margin="0,0,0,43"/>
        <Button Content="Bind Data" Click="Button_Click" Height="43" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="85"/>
        <Button Content="Change First Rec" Margin="85,0,106,0" Height="43" VerticalAlignment="Bottom" Click="Button_Click_1"/>
        <Button Content="Refresh DG" Height="43" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="106" Click="Button_Click_2"/>

    </Grid>
</Window>



Is this possible to do without having the call the refresh?

I want to be able to edit the underlying list of objects and have the change directly reflected to my datagrid, is this possible?

Thanks
Posted

1 solution

Proper solution is that your viewmodels implement INotifyPropertyChanged and you use ObservableCollection
 
Share this answer
 
Comments
BenJBaker╣ 23-Feb-15 7:41am    
If my object is from an entity framework model, can I make it so all entity's of the model implement INotifyPropertyChanged? Without having to manually change each entity?
stibee 23-Feb-15 8:13am    
I my last project I merged the object from entityframework to wrapped elements which implmements I notify property changed.
BenJBaker╣ 23-Feb-15 8:22am    
Thanks, I solved it using this
http://www.codeproject.com/Tips/853383/Adding-INotifyPropertyChanged-to-Entity-Framework

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900