按钮上的ItemsControl的DataTemplate中存在的控件单击

时间:2017-09-11 13:28:46

标签: c# wpf data-binding

我有一个绑定到集合的ItemsControl。

<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>

在按钮的OnClick处理程序中,如何获取tbxcmb的值,这些值是单击按钮的DataTemplate的本地值?

1 个答案:

答案 0 :(得分:0)

试试这个:

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;
}

但请注意,更好的方法是将Text的{​​{1}}属性和TextBox的{​​{1}}属性绑定到{{1}的某些属性而是改为访问这些类。