Wild Goat
Wild Goat

Reputation: 3579

Windows forms to WPF MVVM

I am working on code refactoring from Windows Forms to WPF using MVVM pattern and bindings.

My Windows Form code:

searchCriteriaListBox.Items.Add("Cat");

My WPF XAML:

<ListBox Height="288" HorizontalAlignment="Left" Margin="18,206,0,0" VerticalAlignment="Top" Width="1042" />

How do I implement same 'Add' action using WPF bindings?

Upvotes: 0

Views: 465

Answers (2)

Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

Bind your Listbox to an observable collection, then simply add/remove items from this collection to update, you shouldn't really be adding data to the box in xaml.

Have a look at this video, I found it very useful when learning mvvm - http://www.youtube.com/watch?v=tKfpvs7ZIyo

Upvotes: 2

Tilak
Tilak

Reputation: 30728

Set DataContext of the Page/Window/UserControl (what ever is at root level), to ViewModel.

Create property Items in ViewModel.

use following as binding for searchCriteriaListBox

 {Binding Items, Mode=TwoWay}

<ListBox  ItemsSource="{Binding Items, Mode=TwoWay}" Height="288" HorizontalAlignment="Left" Margin="18,206,0,0" VerticalAlignment="Top" Width="1042" />

In the view model, put an AddItemCommand.

In the AddItemCommand.Execute, add item to Items collection

Use MVVM Light for bits of reusable items, and read WPF Apps With The Model-View-ViewModel Design Pattern

Upvotes: 3

Related Questions