简体   繁体   中英

Entity Framework & Binding synchronisation

Imagine I have an entity:

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

And I have a 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:

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

Here is the problem - this object needs to update in the UI to. 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. You need to use an ObservableCollection<T> which is a copy of your ObjectQuery<T> ; when you add an item to the ObjectQuery<T> , also add it to the 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. This way you get always both worlds updated: WPF and Entity Framework.

You can download the sample application here: WPF Application Framework (WAF) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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