1

我正在尝试学习 WPF 并试图找出将我的LINQ to SQL类绑定到WPF 窗口的最佳方法。

到目前为止,我有这个:

using (Database.DataClasses1DataContext db = new Database.DataClasses1DataContext())
{
    var user = db.Users.Where(u => u.Email == TextboxEmail.Text).FirstOrDefault();
    CustomerTab.DataContext = user;
}

XAML中

<TextBox Name="TextboxContactName" Grid.Row="1" Margin="0,2" Grid.Column="1" Text="{Binding Path=ContactName, UpdateSourceTrigger=LostFocus, Mode=TwoWay}"></TextBox>

因此,这提供了一种将名称显示到文本框的单向绑定。

我一直在尝试在线跟踪示例,但我的问题是,当文本框失去焦点时,如何使其自动更新 LINQ。

我需要在失去焦点事件中手动输入它吗?

编辑 我试图在文本框失去焦点时运行它:

   using (Database.DataClasses1DataContext db = new Database.DataClasses1DataContext())
    {
        Database.User customer = (Database.User)CustomerTab.DataContext;

        db.SubmitChanges();
    }

但客户对象没有更新。我知道我可以这样做:

customer.ContactName = textbox.Text;
db.submitChanges();

但我认为 WPF 应该为我处理这个问题?

4

2 回答 2

1

you should at least add a layer of abstraction between the UI and the Data layer. In order to get the data persisted you need to save the context, not just to update the property in the user object. it's not a best practice anyway, and try to think about the fact that everytime the textbox lost focus there is a trip to the database. anyway adding an abstraction layer, and saving the context in the setter of the property should work for you.

于 2012-04-22T21:04:27.753 回答
0

我对绑定没有什么经验,但是在你的 XAML 中试试这个:

<TextBox Name="TextboxContactName" Grid.Row="1" Margin="0,2" Grid.Column="1" Text="{Binding Path=ContactName, UpdateSourceTrigger=LostFocus}"></TextBox>

编辑1:

Fine print - “UpdateSourceTrigger 属性指定何时使用更改更新源。这仅适用于 Mode=TwoWay 绑定(这是默认设置)。”

编辑2:

如果这不起作用,您可能需要显式调用SubmitChanges().DataContext

于 2012-04-22T21:00:26.043 回答