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 关注
- 1754 浏览
添加回答
举报
0/150
提交
取消