2012-06-27 105 views
0

我正在使用MVVM模式和綁定從Windows窗體到WPF的代碼重構。Windows窗體到WPF MVVM

我的Windows窗體代碼:

searchCriteriaListBox.Items.Add("Cat"); 

我的WPF XAML:

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

如何實現使用WPF綁定相同的 '添加' 行動?

+0

我不認爲一行代碼就足夠讓我們能夠告訴你如何最有效地轉化這個.. 。 – BoltClock

回答

3

設置頁面/窗口/用戶控件的DataContext(永遠在根級別),ViewModel。

在ViewModel中創建屬性Items

使用以下作爲用於searchCriteriaListBox

{Binding Items, Mode=TwoWay} 

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

結合在視圖模型,把一個AddItemCommand。

在AddItemCommand.Execute,添加物品到物品收集

使用MVVM Light可重複使用的物品位,讀WPF Apps With The Model-View-ViewModel Design Pattern

2

您綁定列表框可觀察集合,然後只需添加/刪除此項目集合更新,你不應該真的在xaml的框中添加數據。

看一看這個視頻,我發現它非常有用,當學習MVVM - http://www.youtube.com/watch?v=tKfpvs7ZIyo