我正在重构一个简单的应用程序以遵循 MVVM,我的问题是如何将 SelectionChanged 事件从我的代码中移到 viewModel 后面?我看过一些将元素绑定(bind)到命令的例子,但并没有完全掌握它。任何人都可以提供帮助。谢谢!
任何人都可以使用下面的代码提供解决方案吗?非常感谢!
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;
}
}
最佳答案
您应该将 EventTrigger
与来自 Windows.Interactivity 命名空间的 InvokeCommandAction
结合使用。下面是一个例子:
<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"
。关于c# - WPF 将 UI 事件绑定(bind)到 ViewModel 中的命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4897775/