更新时间:2022-10-21 09:49:09
您应该将 EventTrigger
与 Windows.Interactivity 命名空间中的 InvokeCommandAction
结合使用.下面是一个例子:
<i:Interaction.Triggers><i:EventTrigger EventName="SelectionChanged"><i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"/></i:EventTrigger></i:Interaction.Triggers></列表框>
您可以通过转到添加引用>来引用
.System.Windows.Interactivity
组件 >扩展
完整的 i
命名空间是:xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
.>
I’m doing some refactoring of a simple application to follow MVVM and my question is how do I move a SelectionChanged event out of my code behind to the viewModel? I’ve looked at some examples of binding elements to commands but didn’t quite grasp it. Can anyone assist with this. Thanks!
Can anyone provide a solution using the code below? Many thanks!
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;
}
}
You should use an EventTrigger
in combination with InvokeCommandAction
from the Windows.Interactivity namespace. Here is an example:
<ListBox ...>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
You can reference System.Windows.Interactivity
by going Add reference > Assemblies > Extensions
.
And the full i
namespace is: xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
.