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

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;
    }}


潇潇雨雨
浏览 1712回答 3
3回答

繁花如伊

您应该EventTrigger与InvokeCommandActionWindows.Interactivity命名空间结合使用。这是一个例子:<ListBox&nbsp;...> &nbsp;&nbsp;&nbsp;&nbsp;<i:Interaction.Triggers> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i:EventTrigger&nbsp;EventName="SelectionChanged"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i:InvokeCommandAction&nbsp;Command="{Binding&nbsp;SelectedItemChangedCommand}"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</i:EventTrigger> &nbsp;&nbsp;&nbsp;&nbsp;</i:Interaction.Triggers></ListBox>你可以System.Windows.Interactivity去参考Add reference > Assemblies > Extensions。完整的i命名空间是:xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"。

慕村225694

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

莫回无

要重构这个,你需要改变你的想法。您将不再处理“选择已更改”事件,而是将所选项目存储在viewmodel中。然后,您将使用双向数据绑定,以便在用户选择项目时更新您的viewmodel,并在更改所选项目时更新您的视图。
打开App,查看更多内容
随时随地看视频慕课网APP