I hava a ListBox and Binding Students,I want to get “ID” when I Click “Btn”. But, I don’t know how to do it.Please tell me how to do?
XAML:
<ListBox x:Name="listBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="12">
<TextBlock Text="{Binding Name,StringFormat=Name:\{0\}}"
Foreground="Orange"/>
<TextBlock Text="{Binding Age,StringFormat=Age:\{0\}}"
Foreground="Gray"/>
<Button Content="Get ID Of Student"
x:Name="Btn"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#:
List<Student> students = new List<Student>
{
new Student{Name = "st1",Age = 20,ID = 1},
new Student{Name = "st2",Age = 18,ID = 2},
new Student{Name = "st3",Age = 21,ID = 3},
};
listBox.ItemsSource = students;
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public int ID { get; set; }
}
Bind the
IDfield to theCommandParameterproperty on the buttonThen your
Commandwill automatically get passed theIDas a parameterIf you’re using the
Clickevent instead of theCommandproperty, you can cast thesenderas aButtonand check it’sCommandParameter, or you can cast it’sDataContextas aStudentobject and get the ID from that