开发者

Entity Framework & Binding synchronisation

开发者 https://www.devze.com 2022-12-22 18:02 出处:网络
Imagine I have an entity: public class MyObject { public string Name { get; set; } } And I have a ListBox:

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.MyObjectS开发者_开发技巧et;
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).

0

精彩评论

暂无评论...
验证码 换一张
取 消