简体   繁体   English

实体框架和绑定同步

[英]Entity Framework & Binding synchronisation

Imagine I have an entity: 假设我有一个实体:

public class MyObject
{
    public string Name { get; set; }
}

And I have a ListBox: 我有一个ListBox:

<ListBox x:Name="lbParts">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I bind it to a collection in code-behind: 我将其绑定到代码隐藏的集合中:

ObjectQuery<MyObject> componentQuery = context.MyObjectSet;
Binding b = new Binding();
b.Source = componentQuery;
lbParts.SetBinding(ListBox.ItemsSourceProperty, b);

And the on a button click I add an entity to the MyObjectSet: 然后在按钮上单击“我将实体添加到MyObjectSet”:

var myObject = new MyObject { Name = "Test" };
context.AddToMyObjectSet(myObject);

Here is the problem - this object needs to update in the UI to. 这里是问题-该对象需要在UI中更新到。 But it is not added there :( 但它没有添加到那里:(

The ObjectQuery<T> class doesn't implement the INotifyCollectionChanged interface, so it doesn't notify the UI when an item is added or removed. ObjectQuery<T>类未实现INotifyCollectionChanged接口,因此在添加或删除项目时不会通知UI。 You need to use an ObservableCollection<T> which is a copy of your ObjectQuery<T> ; 您需要使用ObservableCollection<T> ,它是ObjectQuery<T>的副本; when you add an item to the ObjectQuery<T> , also add it to the ObservableCollection<T> . 将项目添加到ObjectQuery<T> ,还应将其添加到ObservableCollection<T>

Binding : 捆绑 :

private ObservableCollection<MyObject> _myObjects;
...

_myObjects = new ObservableCollection(context.MyObjectSet);
Binding b = new Binding();
b.Source = _myObjects;
lbParts.SetBinding(ListBox.ItemsSourceProperty, b);

Add item : 添加项目 :

var myObject = new MyObject { Name = "Test" };
context.AddToMyObjectSet(myObject);
_myObjects.Add(myObject);

The BookLibrary sample application is using an EntityObservableCollection. BookLibrary示例应用程序正在使用EntityObservableCollection。 This way you get always both worlds updated: WPF and Entity Framework. 这样,您将始终获得更新:WPF和实体框架。

You can download the sample application here: WPF Application Framework (WAF) . 您可以在此处下载示例应用程序: WPF应用程序框架(WAF)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM