我正在做一些簡單的應用程序的重構,以遵循MVVM和我的問題是如何將SelectionChanged事件移出我的代碼後面到viewModel?我已經看過一些命令的綁定元素的例子,但並沒有完全理解它。任何人都可以協助這一點。謝謝!WPF綁定UI事件ViewModel中的命令
任何人都可以使用下面的代碼提供解決方案嗎?非常感謝!
public partial class MyAppView : Window
{
public MyAppView()
{
InitializeComponent();
this.DataContext = new MyAppViewModel();
// Insert code required on object creation below this point.
}
private void contactsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
//TODO: Add event handler implementation here.
//for each selected contact get the labels and put in collection
ObservableCollection<AggregatedLabelModel> contactListLabels = new ObservableCollection<AggregatedLabelModel>();
foreach (ContactListModel contactList in contactsList.SelectedItems)
{
foreach (AggregatedLabelModel aggLabel in contactList.AggLabels)
{
contactListLabels.Add(aggLabel);
}
}
//aggregate the contactListLabels by name
ListCollectionView selectedLabelsView = new ListCollectionView(contactListLabels);
selectedLabelsView.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
tagsList.ItemsSource = selectedLabelsView.Groups;
}
}
感謝。我是編程的新手,所以原諒我 - 你能用我提供的代碼舉個例子嗎? – Ben 2011-02-06 21:49:18
您基本上需要在ViewModel中創建一個名爲「SelectedItemChangedCommand」的命令屬性。命令與事件類似,但命令不同於事件,只能有一個回調函數。檢查文檔:http://msdn.microsoft.com/en-us/library/ms752308.aspx – Brian 2011-02-13 01:55:08
如果您沒有Expression Blend,則需要SDK:http://www.microsoft.com/downloads/ en/details.aspx?FamilyID = D197F51A-DE07-4EDF-9CBA-1F1B4A22110D&displaylang = en – Murven 2011-02-14 04:06:34