Nick Tucker
Nick Tucker

Reputation: 347

Reacting mouse click event in viewModel instead of code behind

I have a WPF app where a list view is set via a ViewModel.

I have something like the code below to handle a mouse click on the list view but I have read iot would be better to handle this in the view model instead of the code behind?

I have code like below

XAML:

<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...

Code behind:

private void listView_Click(object sender, RoutedEventArgs e)
{
    var item = (sender as ListView).SelectedItem;
    if (item != null)
    {
        ...
    }
}

I tried have something like the code below but is there a way to move it to the view model avoiding the code behind completely?

public void listView_Click(object sender,RoutedEventArgs e)
{
    var item = (sender as ListView).SelectedItem;
    if (item != null)
    {
        Record record = item.DataContext as Record;
        if (record != null)
        {
            MyViewModel viewModel = ((MyViewModel)this.DataContext);
            var result = viewModel.performWork(record);
        }
    }
}

Note: Record is a ListViewItem

Thanks, Nick

Upvotes: 1

Views: 693

Answers (1)

Fede
Fede

Reputation: 44028

Bind the ListView.SelectedItem property to a property of type Record in your ViewModel (such as SelectedRecord) and perform your work when the selected record changes:

XAML:

<ListView .... 
          SelectedItem="{Binding SelectedRecord}"/>

ViewModel:

private Record _selectedRecord;
public Record SelectedRecord
{
    get { return _selectedRecord; }
    set
    {
        _selectedRecord = value;
        OnPropertyChanged();

        // Call your DoWork() method here
        this.DoWork();
    }
}

Upvotes: 2

Related Questions