WPF将datagrid绑定到对象更改时自动更新的对象列表 [英] WPF Binding datagrid to list of objects automatically updating when an object is changed

查看:125
本文介绍了WPF将datagrid绑定到对象更改时自动更新的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据网格绑定到对象列表并使其成为当我更新列表中的对象时,更改会直接反映到数据网格中而无需调用刷新。



我的代码是:



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:

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:




XAML:

<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

推荐答案

正确的解决方案是你的viewmodel实现INotifyPropertyChanged并使用ObservableCollection
Proper solution is that your viewmodels implement INotifyPropertyChanged and you use ObservableCollection


这篇关于WPF将datagrid绑定到对象更改时自动更新的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆