views:

352

answers:

3

I can add a Combobox to a DataGrid using following xmal:

 <local:DataGridTemplateColumn Header="SomeHeader" Width="106" HeaderStyle="{StaticResource headerAlignRightStyle}" CellStyle="{StaticResource cellAlignRightStyle}">
                    <local:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding SomeProp}" Margin="4"/>
                        </DataTemplate>
                    </local:DataGridTemplateColumn.CellTemplate>
                    <local:DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <ComboBox 
                              x:Name="SomeCombo"
                              SelectionChanged="SomeCombo_SelectionChanged"
                              ItemsSource="{Binding SomeList}"
                              DisplayMemberPath="Name" 
                              />
                        </DataTemplate>
                    </local:DataGridTemplateColumn.CellEditingTemplate>
                </local:DataGridTemplateColumn>

However what I can't figure out is a sensible way to get the row that was combox is bound to. i.e. when handling the combobox SelectionChanged event I have no way of knowing what what row the combobox belongs to. Particularly I don't know what object in the DataGrid datasource that the combobox is refering to.

Any help would be much appreciated.

A: 

As I understand it, when you are clicking on the combo box, that row should get focus. This also means that the datagrid is aware of the selected item.

If you are looking for the selected object, you should have access to it with datagridName.SelectedItem. This will return the selected object.

Please test it and comment on the solution as I am unable to check the answer right now.

Johannes
A: 

Hi there,

you could

A) Bind the SelectedItem property of the ComboBox to a property in your ViewModel/data model using a two way binding, so you wouldn't have to worry about SelectionChanged in the first place

or

B) Use DataGridRow.GetRowContainingElement(element) in your SelectionChanged handler, i.e.

private void SomeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var comboBox = sender as ComboBox;
    if (comboBox == null)
        return;
    var row = DataGridRow.GetRowContainingElement(comboBox);
    // Do something with row...
}

Cheers, Alex

alexander.biskop
Thanks - I'm now looking into mvvm properly...
bplus
A: 

If you are just looking to get the item the row is bound to, you can just read the DataContext of the sender:

private void SomeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var item = sender as FrameworkElement;
    if (item== null)
        return;
    var source = item.DataContext;
}
Stephan