【问题标题】:Bind ObservableCollection to database将 ObservableCollection 绑定到数据库
【发布时间】:2011-08-16 11:45:16
【问题描述】:

我有以下课程:

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

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

下面的代码是为了从我的数据库表“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);

如何根据我的ObservableCollection 更新数据库?

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    使用 ItemTemplate 或任何其他 ItemsControl 将项目绑定到 ListBox。

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

    在后面的代码中设置数据上下文:

    myListBox.DataContext = items;
    

    然后添加一个带有执行 dataContext.SubmitChanges 事件的按钮

    【讨论】:

    • nonono 您解释了如何将集合绑定到 UI。我想绑定它 mySqlServer
    【解决方案2】:

    我不久前写的这篇代码项目文章有一个部分详细介绍了从绑定的 WPF 数据网格执行数据库更新/删除/插入操作:

    WPF DataGrid Practical Examples

    【讨论】:

      猜你喜欢
      • 2014-09-28
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2011-04-10
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多