I am using a DataGrid in my Silverlight project which contains a custom checkbox column. I have bound its Command property to a property of my ViewModel class. Now, the problem is that I want to send the “selected item” of DataGrid through the command parameter for which I have written the following code :
<sdk:DataGrid AutoGenerateColumns="False" Margin="10,0,10,0" Name="dataGridOrders" ItemsSource="{Binding OrderList}" Height="190">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header="Select">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox>
<is:Interaction.Triggers>
<is:EventTrigger EventName="Checked">
<is:InvokeCommandAction Command="{Binding Source={StaticResource ExecutionTraderHomePageVM},Path=OrderSelectedCommand,Mode=TwoWay}"
CommandParameter="{Binding ElementName=dataGridOrders,Path=SelectedItem}" />
</is:EventTrigger>
<is:EventTrigger EventName="Unchecked">
<is:InvokeCommandAction Command="{Binding Source={StaticResource ExecutionTraderHomePageVM},Path=OrderSelectedCommand,Mode=TwoWay}"
CommandParameter="{Binding ElementName=dataGridOrders,Path=SelectedItem}" />
</is:EventTrigger>
</is:Interaction.Triggers>
</CheckBox>
But I am always getting null in the parameter of my command’s Execute method. I have tried with other properties of DataGrid such as Width, ActualHeight etc. but of no use. What am I missing here?
The problem here is one of name-scoping. In short, the XAML inside a
DataTemplatehas its own ‘namescope’ and can’t see any names outside of it. In particular, it won’t be able to find the parentDataGridas that lies outside theDataTemplate.I’m not sure why you’re listening out to checked and unchecked events and firing commands based on them. It’s not entirely clear what you’re trying to achieve. Instead, I would use a two-way binding to bind the
IsCheckedproperty of theCheckBoxto aboolproperty in your (row-level) view-model class, and call the command functionality from thisboolproperty’s setter. You can get hold of the selected item by binding a view-model property to theDataGridsSelectedItemproperty with a two-way binding.