WPF將UI事件綁定到ViewModel中的命令我正在做一些簡單的應用程序重構以跟隨MVVM,我的問題是如何將SelectionChanged事件從我的代碼中移出到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;
}}
3 回答

繁花如伊
TA貢獻2012條經驗 獲得超12個贊
您應該EventTrigger
與InvokeCommandAction
Windows.Interactivity命名空間結合使用。這是一個例子:
<ListBox ...> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"/> </i:EventTrigger> </i:Interaction.Triggers></ListBox>
你可以System.Windows.Interactivity
去參考Add reference > Assemblies > Extensions
。
完整的i
命名空間是:xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
。

莫回無
TA貢獻1865條經驗 獲得超7個贊
要重構這個,你需要改變你的想法。您將不再處理“選擇已更改”事件,而是將所選項目存儲在viewmodel中。然后,您將使用雙向數據綁定,以便在用戶選擇項目時更新您的viewmodel,并在更改所選項目時更新您的視圖。
- 3 回答
- 0 關注
- 1822 瀏覽
添加回答
舉報
0/150
提交
取消