Twoway databinding to a MongoDB collection in WPF

I’ll show how to have a two-way databinding between a templated listbox and a MongoDB collection.
I’m finally got around toying with MongoDb.What I’ll show next might not be the most correct way, but it works for me.

Setup

I have a Listview defined in XAML with a datatemplate:

        <ListBox Name="mylistbox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Naam, Mode=TwoWay}"></TextBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

I created an Entity class (can be a composite if you wish) which is is simple POCO with INotifyPropertyChanged implemented. This Entity class will be serialized to my MongoDB collection as-is. Explained here, for example:

        public class Entity
        {
            public string Naam { get; set; }
        }

Retrieve the data and databind

Next up, we need to retrieve the data using a query (coll being my collection a retrieved earlier on (not shown)):

var query = coll.AsQueryable<Entity>().ToList();

The ToList part is important. This will ensure that we get a simple list of Entity objects as our ItemSource and not an IQueryable, otherwise the next part won’t work.

Write changes to the database

You can now edit your data in your listbox and once you are ready, you can update all the changes to your MongoDB collection:

            foreach (var item in mylistbox.ItemsSource)
            {
                coll.Save(item);
            }

Een gedachte over “Twoway databinding to a MongoDB collection in WPF

Geef een reactie

Vul je gegevens in of klik op een icoon om in te loggen.

WordPress.com logo

Je reageert onder je WordPress.com account. Log uit /  Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log uit /  Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit /  Bijwerken )

Verbinden met %s

Deze site gebruikt Akismet om spam te bestrijden. Ontdek hoe de data van je reactie verwerkt wordt.

%d bloggers liken dit:
search previous next tag category expand menu location phone mail time cart zoom edit close