views:

50

answers:

2

* EDIT * Sorry, I should make it clearer. 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 :(

Help!

+1  A: 

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);
Thomas Levesque
Thanks for the help.
Jefim
A: 

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).

jbe