【问题标题】:How to automatically update TableAdapter bound to TextBox如何自动更新绑定到 TextBox 的 TableAdapter
【发布时间】:2023-03-26 14:40:01
【问题描述】:

我有一个 WPF 窗口,上面有几个文本框。

我有一个附加到 SQL 服务器数据库的 XSD 数据集,并且窗口绑定到 tableadapter 中的一行:

  public partial class PersonForm : Window
  {
    public PersonForm(int id)
    {
      InitializeComponent();

      MyDatasetTableAdapters.personTableAdapter tableAdapter = 
        new MyDatasetTableAdapters.personTableAdapter();

      personRow row = tableAdapter.GetPersonById(id);

      this.DataContext = row;
    }

    ...

  }

文本框是这样绑定的:

<TextBox Name="lastName" Text="{Binding Path=lastname}" />

这些绑定绑定有效,文本框已正确填充 SQL 数据库中的数据,但在编辑文本框时,更改不会传播回数据库。

我有一个按钮,点击后会调用

myTableAdapter.Update(myRow);

这确实成功更新了 SQL 数据库。

我的问题是:我需要进行哪些更改才能使文本框自动更新数据库(无需显式调用 TableAdapter.Update)。

另外,这是在 WPF 中将表单绑定到数据库的正确方法吗?

【问题讨论】:

    标签: wpf windows database binding


    【解决方案1】:

    我发现了一种方法来实现这一点。

    通过在文本框绑定上将 NotifyOnSourceUpdated 属性设置为 True,如下所示:

    <TextBox Name="lastName" Text="{Binding Path=lastname, NotifyOnSourceUpdated=True}" />
    

    然后我可以像这样在 Window 的 SourceUpdated 事件中更新表适配器:

    private void Window_SourceUpdated(object sender, DataTransferEventArgs e)
    {
      myTableAdapter.Update(myRow);
    }
    

    这似乎运作良好。有没有更好的方法来实现这一点?

    有没有一种方法可以轻松地在所有文本框上启用 NotifyOnSourceUpdated 而无需在每个 TextBox 上指定它?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多