MainWindow.xaml:
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<DataGrid x:Name="dg" Height="260" Width="290" ItemsSource="{Binding Items}" SelectionMode="Single"
AutoGenerateColumns="False" SelectionUnit="FullRow" SelectionChanged="dg_SelectionChanged" >
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DoSelectedRow"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn x:Name="ID" Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn x:Name="FullName" Header="FullName" Binding="{Binding FullName}"/>
<DataGridTextColumn x:Name="Description" Header="Description" Binding="{Binding Description}"/>
</DataGrid.Columns>
</DataGrid>
<StackPanel Grid.Row="1">
<TextBox x:Name="ImID" Width="100" Height="40"/>
<TextBox x:Name="ImFullName" Width="100" Height="40"/>
<TextBox x:Name="ImDescription" Width="100" Height="40"/>
</StackPanel>
</Grid>
MainWindow.xaml.cs:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace DataGridSelected
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid grid = (DataGrid)sender;
dynamic selected_row = grid.SelectedItem;
//ImID.Text= selected_row["ID"].ToString();
}
public void DoSelectedRow(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell != null && !cell.IsEditing)
{
DataGridRow row = FindVisualParent<DataGridRow>(cell);
if (row != null)
{
row.IsSelected = !row.IsSelected;
e.Handled = true;
}
}
}
public static Parent FindVisualParent<Parent>(DependencyObject child) where Parent : DependencyObject
{
DependencyObject parentObject = child;
while (!((parentObject is System.Windows.Media.Visual)
|| (parentObject is System.Windows.Media.Media3D.Visual3D)))
{
if (parentObject is Parent || parentObject == null)
{
return parentObject as Parent;
}
else
{
parentObject = (parentObject as FrameworkContentElement).Parent;
}
}
parentObject = VisualTreeHelper.GetParent(parentObject);
if (parentObject is Parent || parentObject == null)
{
return parentObject as Parent;
}
else
{
return FindVisualParent<Parent>(parentObject);
}
}
}
public class ViewModel : INotifyPropertyChanged
{
private int _selectedIndex = 0;
public int SelectedIndex
{
get { return _selectedIndex; }
set { _selectedIndex = value; OnPropertyChanged("SelectedIndex"); }
}
private ObservableCollection<Item> items = new ObservableCollection<Item>();
public ObservableCollection<Item> Items
{
get { return items; }
set { items = value; }
}
public ViewModel()
{
Items.Add(new Item() { ID="1", FullName="image1", Description = "image1" });
Items.Add(new Item() { ID = "2", FullName = "image2", Description = "image2" });
Items.Add(new Item() { ID = "3", FullName = "image3", Description = "image3" });
Items.Add(new Item() { ID = "4", FullName = "image4", Description = "image4" });
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Item : INotifyPropertyChanged
{
private string id;
public string ID
{
get { return id; }
set { id = value; OnPropertyChanged("ID"); }
}
private string fullName;
public string FullName
{
get { return fullName; }
set { fullName = value; OnPropertyChanged("FullName"); }
}
private string description;
public string Description
{
get { return description; }
set { description = value; OnPropertyChanged("Description"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The result:
Update:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<DataGrid x:Name="dg" Height="260" Width="290" SelectionMode="Single" AutoGenerateColumns="False"
SelectionUnit="FullRow" SelectionChanged="dg_SelectionChanged" >
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DoSelectedRow"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn x:Name="ID" Header="ID" Binding="{Binding Id}"/>
<DataGridTextColumn x:Name="FullName" Header="FullName" Binding="{Binding FullName}"/>
<DataGridTextColumn x:Name="Description" Header="Description" Binding="{Binding Description}"/>
</DataGrid.Columns>
</DataGrid>
<TextBox x:Name="ImID" Grid.Row="1" Width="100" Height="50" />
</Grid>
MainWindow.xaml.cs:
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace DataGridSelected
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
FillGrid();
}
private void FillGrid()
{
string constr = @"constr";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("Select * From [dbo].[Table]", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
var dt = new DataTable();
da.Fill(dt);
dg.ItemsSource = dt.DefaultView;
List<int> SelectedIndexs = dg.SelectedItems
.Cast<DataRowView>()
.Select(view => dt.Rows.IndexOf(view.Row))
.ToList();
con.Close();
}
private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid grid = (DataGrid)sender;
dynamic selected_row = grid.SelectedItem;
if (selected_row == null)
{
ImID.Text = "";
}
else
{
ImID.Text = selected_row["ID"].ToString();
}
}
public void DoSelectedRow(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell != null && !cell.IsEditing)
{
DataGridRow row = FindVisualParent<DataGridRow>(cell);
if (row != null)
{
row.IsSelected = !row.IsSelected;
e.Handled = true;
}
}
}
public static Parent FindVisualParent<Parent>(DependencyObject child) where Parent : DependencyObject
{
DependencyObject parentObject = child;
while (!((parentObject is System.Windows.Media.Visual)
|| (parentObject is System.Windows.Media.Media3D.Visual3D)))
{
if (parentObject is Parent || parentObject == null)
{
return parentObject as Parent;
}
else
{
parentObject = (parentObject as FrameworkContentElement).Parent;
}
}
parentObject = VisualTreeHelper.GetParent(parentObject);
if (parentObject is Parent || parentObject == null)
{
return parentObject as Parent;
}
else
{
return FindVisualParent<Parent>(parentObject);
}
}
}
}
The result:
selected item 4:
unselected item 4:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.