Reputation: 565
Hi I have a telerik RadGridView bound up to an observable collection via MVVM and the SelectedItem
property of the grid is also bound to a property from within the model as well. There is then a button column that is bound to open the selected item to see more details of the selected item. The code for this is below.
<telerik:RadGridView Name="RadGridView"
Height="900"
AutoGenerateColumns="False"
CanUserSortColumns="True"
IsReadOnly="True"
ItemsSource="{Binding Model.Items}"
SelectedItem="{Binding Model.SelectedItem,Mode=TwoWay}"
Width="990">
<telerik:RadGridView.Columns>
<telerik:GridViewColumn Header="Open Item" >
<telerik:GridViewColumn.CellTemplate>
<DataTemplate>
<Button Content="Open"
Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand,
RelativeSource= {RelativeSource FindAncestor,
AncestorType={x:Type telerik:RadGridView}}}">
</Button>
</DataTemplate>
</telerik:GridViewColumn.CellTemplate>
</telerik:GridViewColumn>
<telerik:GridViewDataColumn DataMemberBinding="{Binding DateScanned}" Header="Date Scanned" />
<telerik:GridViewDataColumn DataMemberBinding="{Binding Amount}" Header="Amount" />
<telerik:GridViewDataColumn DataMemberBinding="{Binding Description}" Header="Description" />
<telerik:GridViewDataColumn DataMemberBinding="{Binding IsRefund}" Header="Is Refund" />
</telerik:RadGridView.Columns>
</telerik:RadGridView>
Now this code works fine whenever I click into the row then click the button, however if I just click the button of the row without clicking into the row first the SelectedItem
property is not set and so the command does not function as expected.
I thought when clicking the button of a row it would auto select that row but apparently not. Does anyone know how I can get it to set the SelectedItem
property whenever I only click on the button within a specific row without having to click on the row before clicking the button?
Upvotes: 1
Views: 2795
Reputation: 169200
You could pass a reference to the underlying data object as a command parameter to the command:
<Button Content="Open"
Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type telerik:RadGridView}}}"
CommandParameter="{Binding}">
</Button>
For the row to actually become selected when you click on the Button
, you will have to write some code that actually selects it. You could do this by handling the Button
's Click
event like this:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
RadGridView.SelectedItem = button.DataContext;
}
<Button Content="Open"
Click="Button_Click_1"
Command="{Binding Path=DataContext.OpenItemBySelectedItemCommand,
RelativeSource= {RelativeSource FindAncestor,
AncestorType={x:Type telerik:RadGridView}}}">
</Button>
This does not break the MVVM pattern since selecting a row in the view is pure view functionality.
Upvotes: 4