views:

133

answers:

2

Lets say I've got a DataTemplate like so

 <DataTemplate x:Key="Body">
   <StackPanel Orientation="Horizontal">
     <ComboBox ItemsSource="{Binding Path=Person.Children}"></ComboBox>
     <Button Click="Button_Click">Hello</Button>
   </StackPanel>
 </DataTemplate>

Which shows a list of ComboBoxes followed by a button.

Now, on clicking the button I need to discover the value in the combo next to the button pressed. I can get the data context as below but can't work out how to get the combos SelectedItem

private void Button_Click(object sender, RoutedEventArgs e)
{
   // Can get the data context
   var p = ((Button)sender).DataContext as Person;

   // How to get the value in the combo ...?
}
A: 

Instead of using the Click event handler, use a Command and bind the CommandParameter property to the ComboBox.SelectedItem. Then in your command's executed logic, you can use the parameter.

Charlie
A: 

you can also reference the combobox in your codebehind if you give it a name. However its cleaner to use a separate class to do your logic than the code behind. Such as a viewmodel.

then you could also do something like this...

            <DataTemplate x:Key="Body">
                <StackPanel Orientation="Horizontal">
                    <ComboBox ItemsSource="{Binding Path=Person.Children}"
                        SelectedItem="{Binding Path=SelectedChild}"
                        IsSynchronizedWithCurrentItem="True"/>
                    <Button Command="{Binding Path=ButtonCommand}">Hello</Button>
                </StackPanel>
            </DataTemplate>
ecathell