为了账号安全,请及时绑定邮箱和手机立即绑定

WPF将UI事件绑定到ViewModel中的命令

WPF将UI事件绑定到ViewModel中的命令

C#
潇潇雨雨 2019-08-12 18:05:26
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个赞

您应该EventTriggerInvokeCommandActionWindows.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"


查看完整回答
反对 回复 2019-08-12
?
慕村225694

TA贡献1880条经验 获得超4个赞

我处理这个问题的方法是在ViewModel中有一个SelectedItem属性,然后将ListBox的SelectedItem绑定到该属性。


查看完整回答
反对 回复 2019-08-12
?
莫回无

TA贡献1865条经验 获得超7个赞

要重构这个,你需要改变你的想法。您将不再处理“选择已更改”事件,而是将所选项目存储在viewmodel中。然后,您将使用双向数据绑定,以便在用户选择项目时更新您的viewmodel,并在更改所选项目时更新您的视图。


查看完整回答
反对 回复 2019-08-12
  • 3 回答
  • 0 关注
  • 1706 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信