Bind ObservableCollection to database

限于喜欢 提交于 2020-01-25 10:52:08

问题


I have the following class:

[Table]
public class myClass
{
    [Column(IsPrimaryKey = true)]
    public int ID { get; set; }

    [Column]
    public string Type { get; set; }
}

And the following code in order to load the data from my database table "myClass":

static public readonly ObservableCollection<myClass> items;
DataContext dataContext = new DataContext("Secret");

var ruleTable = dataContext.GetTable<myClass>();

IQueryable<Rule> custQuery = ruleTable.Select(tableName => tableName);
items = new ObservableCollection<myClass>(custQuery);

How can I make the database update based on my ObservableCollection?


回答1:


Bind the items to a ListBox with an ItemTemplate or any other ItemsControl.

<ListBox x:Name="myListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Content="{Binding ID}"/>
                <TextBox Content="{Binding Type, Mode=TwoWay}"/>
            </StackPanel>
        </DataTemplate>
    <ListBox.ItemTemplate>
</ListBox>

Set the datacontext in code behind:

myListBox.DataContext = items;

Then add a button with an event that executes dataContext.SubmitChanges




回答2:


This codeproject article I wrote a while back has a section that details performing database update / delete / insert operations from a bound WPF datagrid:

WPF DataGrid Practical Examples



来源:https://stackoverflow.com/questions/7077699/bind-observablecollection-to-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!