Get DataGrid SelectedRow in Silverlight

摘要:Get DataGrid SelectedRow in Silverlight

I was a bit surprised to find that there is no simpler way to get the selected row. There is however selectedIndex and selectedItem but those are only good for getting the DataContext related to that particular row not the selectedRow.

In here i will show you

1) Get the Context related to the selectedRow
2) Get the selected DataGridRow
3) Color the selectedRow

You can see the live example here [live demo] 

The SOURCE CODE(.zip) is at the end of the page for download.

MainPage.xaml

    <Grid x:Name=”LayoutRoot”>
        <sdk:DataGrid AutoGenerateColumns=”True” Height=”300″ HorizontalAlignment=”Left” Margin=”10,10,0,0″ Name=”dataGrid1″ VerticalAlignment=”Top” Width=”220″ />
    </Grid>

MainPage.xaml.cs

using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Tips
{
    public partial class MainPage : UserControl
    {
        List<DataGridRow> Rows = new List<DataGridRow>();
        public MainPage()
        {
            InitializeComponent();
            dataGrid1.LoadingRow += (sender, e) =>
            {
                var oldRows = Rows.Where(w => w.DataContext.Equals(e.Row.DataContext)).ToList();
                foreach (var row in oldRows)
                {
                    Rows.Remove(row);
                }
                Rows.Add(e.Row);
            };

            dataGrid1.SelectionChanged += new SelectionChangedEventHandler(dataGrid1_SelectionChanged);
            dataGrid1.ItemsSource = PopulateDummyData();

        }

        void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //to get the current row binding value
            Person currentRow = (Person)dataGrid1.SelectedItem;

            //to read the currentRow
            DataGridRow selectedRow = Rows[dataGrid1.SelectedIndex];
            //color row
            var backgroundRectangle = MyVisualTreeHelper.SearchFrameworkElement(selectedRow, “BackgroundRectangle”) as Rectangle;
            if (backgroundRectangle != null)
            {
                backgroundRectangle.Fill = new SolidColorBrush(Colors.Orange);
            }
        }

        private List<Person> PopulateDummyData()
        {
            List<Person> coll = new List<Person>();
            coll.Add(new Person { Id = 1, Name = “Sharker” });
            coll.Add(new Person { Id = 2, Name = “Khaleed” });
            coll.Add(new Person { Id = 3, Name = “Mahmud” });
            coll.Add(new Person { Id = 3, Name = “Follow” });
            coll.Add(new Person { Id = 3, Name = “me” });
            coll.Add(new Person { Id = 3, Name = “at Twitter” });

            return coll.OrderBy(o => o.Name).ToList<Person>();
        }
    }

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