2010-11-05 3 views
2

Кажется, я не могу об этом подумать.Вопрос об индексе сортировки WPF Datagrid

Я создал пример код для демонстрации моего вопроса, надеясь кто-то может направить меня к ответу ...

Выпуск когда DataGrid отсортирован, меченый ID и имя больше не соответствуют выбранному DataGrid пункт.

Я бы appriciate вашей помощи ...

Благодаря

Джефф

<Window x:Class="dgSortTest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="dgSortTest" Height="253" Width="403" IsEnabled="True"> 
    <Grid> 
     <DataGrid AutoGenerateColumns="False" Height="212" HorizontalAlignment="Left" Margin="12,2,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" SelectionChanged="dataGrid1_SelectionChanged" RowHeaderWidth="0" AreRowDetailsFrozen="False" CanUserAddRows="True" CanUserDeleteRows="True" IsReadOnly="True"> 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="ID" Binding="{Binding ID}"/> 
       <DataGridTextColumn Header="Name" Binding="{Binding Name}"/> 
     </DataGrid.Columns> 
     </DataGrid> 
     <Label Content="Index: " Name="lblIndex" Height="28" HorizontalAlignment="Left" Margin="228,12,0,0" VerticalAlignment="Top" Width="92" /> 
     <Label Content="ID:" Name="lblID" Height="28" HorizontalAlignment="Left" Margin="228,46,0,0" VerticalAlignment="Top" Width="141" IsEnabled="True" /> 
     <Label Content="Name: " Name="lblName" Height="28" HorizontalAlignment="Left" Margin="228,80,0,0" VerticalAlignment="Top" Width="141" /> 
    </Grid> 
</Window> 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 

namespace dgSortTest 
{ 
    public partial class MainWindow : Window 
    { 
     List<Person> people = new List<Person>(); 
     public MainWindow() 
     { 
      InitializeComponent(); 
      people.Add(new Person() { ID = 0, Name = "Jeff" }); 
      people.Add(new Person() { ID = 1, Name = "Tom" }); 
      people.Add(new Person() { ID = 2, Name = "Andy" }); 
      people.Add(new Person() { ID = 3, Name = "Ken" }); 
      people.Add(new Person() { ID = 4, Name = "Zack" }); 
      people.Add(new Person() { ID = 5, Name = "Emily" }); 
      people.Add(new Person() { ID = 6, Name = "Courtney" }); 
      people.Add(new Person() { ID = 7, Name = "Adam" }); 
      people.Add(new Person() { ID = 8, Name = "Brenda" }); 
      people.Add(new Person() { ID = 9, Name = "Bill" }); 
      people.Add(new Person() { ID = 10, Name = "Joan" }); 
      dataGrid1.ItemsSource = from Person in people select Person; 
     } 

     private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
     { 
      int index = dataGrid1.SelectedIndex; 
      lblIndex.Content = "Index: " + index.ToString(); 
      lblID.Content = "ID: " + people[index].ID; 
      lblName.Content = "Name: " + people[index].Name; 
     } 
    } 

    public class Person 
    { 
     public int ID { get; set; } 
     public string Name { get; set; } 
    } 
} 

ответ

1

Хорошего описания вашей проблемы и короткой выборки, +1 для этого.

Короткий ответ, чтобы не изменять большую часть вашей текущей реализации, вы можете это сделать.

private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    Person selectedItem = dataGrid1.SelectedItem as Person; 
    int index = dataGrid1.SelectedIndex; 
    lblIndex.Content = "Index: " + index.ToString(); 
    lblID.Content = "ID: " + selectedItem.ID; 
    lblName.Content = "Name: " + selectedItem.Name; 
} 

Однако я бы посоветовал вам напрямую связываться с SelectedItem. Тогда вам не понадобится код, стоящий за EventHandler.

<StackPanel Orientation="Vertical" Margin="228,12,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="92" > 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="Index: "/> 
     <TextBlock Text="{Binding ElementName=dataGrid1, Path=SelectedIndex}"/> 
    </StackPanel> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="ID: "/> 
     <TextBlock Text="{Binding ElementName=dataGrid1, Path=SelectedItem.ID}"/> 
    </StackPanel> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="Name: "/> 
     <TextBlock Text="{Binding ElementName=dataGrid1, Path=SelectedItem.Name}"/> 
    </StackPanel> 
</StackPanel> 
+0

Большое вам спасибо! Я должен сказать, что первое предложение намного легче понять, поскольку TBO, я еще не понимаю, что происходит с xaml. Я в порядке с созданием пользовательского интерфейса с ним, но чтобы сделать большую часть кодирования там, без кода позади, меня смущает. Я уверен со временем, я получу его. –

Смежные вопросы