2012-04-06 84 views
0

我有一個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; } 
     } 

回答

3

綁定ID領域的CommandParameter財產上的按鈕

<Button Content="Get ID Of Student" 
     x:Name="Btn" 
     CommandParameter="{Binding ID}" 
     ... /> 

然後你Command將自動獲得通過的ID作爲參數

如果您正在使用Click事件而不是Command屬性,您可以施放sender作爲Button並檢查它的CommandParameter,或者你可以從

void Btn_Click(object sender, EventArgs e) 
{ 
    Button b = sender as Button; 

    int id = (int)b.CommandParameter; 

    // or 
    Student student = (Student)b.DataContext; 
    int id = student.ID; 
} 
+0

非常感謝你。但在你的方式,如果我需要得到很多財產,如何做到這一點?例如:公開課學生{姓名,年齡,身份證,年級,性別,Brith,城市等等}。我想要得到它們。我認爲「標籤」不夠用 – BillyMadisonnn 2012-04-06 13:06:06

+0

@BillyMadisonnn在我的答案中查看最後兩行代碼。您將'DataContext'轉換爲'Student'對象,然後訪問所有學生屬性。或者,您可以將'CommandParameter'綁定到整個對象('CommandParameter =「{Binding}」'),並將'CommandParameter'強制轉換爲'Student'對象而不是int' – Rachel 2012-04-06 13:09:07

+0

哦。一個好主意!非常感謝你。 – BillyMadisonnn 2012-04-06 13:09:26

0

什麼:

Student selectedStundet = listBox.SelectedItem as Student; 
+0

謝謝。我碰到了ListBoxItem的「Btn」。它不是ListBox,所以我無法得到listBox.SelectItem – BillyMadisonnn 2012-04-06 13:07:50

0
<Button Content="Get ID Of Student" x:Name="Btn" Tag={Binding ID} Click="Button_Click" /> 

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
     Button b = (Button)sender; 
     string id = b.Tag; 
     ... 
} 

投它DataContextStudent對象並獲取ID然後你得到你[R學生使用LINQ,這樣的事情:

Student a = from student in Students 
      student.ID=(int)id 
      select student; 
+0

非常感謝你。但在你的方式,如果我需要得到很多財產,如何做到這一點?例如:公開課學生{姓名,年齡,身份證,年級,性別,Brith,城市等等}。我想要得到它們。我認爲「標籤」不夠用 – BillyMadisonnn 2012-04-06 13:03:19

+0

查看上面的答案,我添加了細節。 – Eugene 2012-04-06 13:10:14

+0

哇。這也是一個解決方案。謝謝 – BillyMadisonnn 2012-04-06 13:12:43

0

試試這個:

private void Btn_Click(object sender, RoutedEventArgs e) 
     { 
      Student st = (sender as Button).DataContext as Student; 
      MessageBox.Show(st.ID + "\n" + st.Age + "\n" + st.Name); 
     }