0

I have an ItemsControl that is bound to a collection.

<ItemsControl ItemsSource="{Binding Classroom.Teachers}">
  <ItemsControl.ItemTemplate>
  <DataTemplate>
  <StackPanel Orientation="Horizontal">
    <TextBox x:Name="tbx" Width="40"/>
    <ComboBox x:Name="cmb" Width="100"/>
    <Button Click="OnClick">
      <TextBlock Text="Add"/>
    </Button>
  </StackPanel>
  <DataTemplate>
</ItemsControl>

In the OnClick handler of the button how to I get the values of tbx and cmb that are local to the DataTemplate of the button which was clicked?

rtkite
  • 37
  • 4
  • You need `FrameworkTemplate.FindName Method (String, FrameworkElement)` for this purpose like the duplicate one. – Salah Akbari Sep 11 '17 at 13:32

1 Answers1

0

Try this:

private void OnClick(object sender, RoutedEventArgs e)
{
    Button btn = sender as Button;
    Panel panel = btn.Parent as Panel;

    TextBox tbx = panel.Children[0] as TextBox;
    string s = tbx.Text;

    ComboBox cmb = panel.Children[1] as ComboBox;
    object item = cmb.SelectedItem;
}

But note that a better approach would be to bind the Text property of the TextBox and the SelectedItem property of the ComboBox to some properties of your Teacher class and access these instead.

mm8
  • 163,881
  • 10
  • 57
  • 88