Working with Grid SelectedItems without any line of code in code behind

This is another blog related to creating clean separation of View and ViewModel. When you use Grid and have to act on a single selected item, just pass ‘SelectedItem’ in the command parameter. What happens when you need to act with multiple rows, it is also as simple as using SelectedItems in the command parameter. With this you do not need to write anything in the code behind, especially navigate through the collection of selected items to publish the result to ViewModel. I do not like this idea of coding in code behind in this scenario, especially you are exposing the model to the view when you are boxing individual elements. If you would expose the Model to View then you are breaking the fundamental MVVM pattern. Fortunately we can achieve this without any line of code in the code behind.

XAML

<Button Content="Selected Items" Command="{Binding SelectedItemsCmd}" CommandParameter="{Binding ElementName=grid, Path=SelectedItems}" Grid.Column="1" />
 <c1:C1FlexGrid Name="grid" ItemsSource="{Binding Rows}" AutoGenerateColumns="True" Grid.ColumnSpan="2" Grid.Row="1" />

In XAML binding, we say we are going to execute ‘SelectedItemsCmd’ which takes all Selected Items from the grid as the parameter.

ViewModel

 

public IActionCommand<object> SelectedItemsCmd { get; set; }

        public void SelectedItemsTest(object parameter)
        {
            List<string> temp = new List<string>();
            foreach(var item  in (IList)parameter)
            {
                temp.Add(item.ToString());
            }
        }

 

I am using Jounce as my MVVM framework and Component One for my grid control. Component One returns IList of objects. So in my case, the data binding happens to be List<string> so I walk through the returned object collection and cast each object the I need to box and I use it in my View Model. Thanks to Bernardo @ Component One for help clarify IList for me.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s