0

我有一个列表框和绑定学生,我想在单击“Btn”时获取“ID”。但是,我不知道该怎么做。请告诉我该怎么做?

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

4 回答 4

3

ID将字段绑定到CommandParameter按钮上的属性

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

然后你Command会自动得到ID作为参数传递

如果您使用Click事件而不是Command属性,则可以将其转换sender为 aButton并检查它的CommandParameter,或者您可以将其转换DataContextStudent对象并从中获取 ID

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;
}
于 2012-04-06T12:58:45.697 回答
0

关于什么:

Student selectedStundet = listBox.SelectedItem as Student;
于 2012-04-06T12:58:35.390 回答
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;
        ...
}

然后你让你的学生使用 LINQ,如下所示:

Student a = from student in Students
          student.ID=(int)id
          select student; 
于 2012-04-06T13:00:01.863 回答
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);
        }
于 2012-04-06T15:25:12.287 回答