我有一個ListBox和綁定的學生,當我點擊「Btn」時我想獲得「ID」。但是,我不知道該怎麼做。請告訴我該怎麼做?如何從ListBoxItem的控件獲取值?
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; }
}
非常感謝你。但在你的方式,如果我需要得到很多財產,如何做到這一點?例如:公開課學生{姓名,年齡,身份證,年級,性別,Brith,城市等等}。我想要得到它們。我認爲「標籤」不夠用 – BillyMadisonnn 2012-04-06 13:06:06
@BillyMadisonnn在我的答案中查看最後兩行代碼。您將'DataContext'轉換爲'Student'對象,然後訪問所有學生屬性。或者,您可以將'CommandParameter'綁定到整個對象('CommandParameter =「{Binding}」'),並將'CommandParameter'強制轉換爲'Student'對象而不是int' – Rachel 2012-04-06 13:09:07
哦。一個好主意!非常感謝你。 – BillyMadisonnn 2012-04-06 13:09:26