我有一个绑定到集合的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
处理程序中,如何获取tbx
和cmb
的值,这些值是单击按钮的DataTemplate的本地值?
答案 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}的某些属性而是改为访问这些类。