Your question is lacking in detail and your code is incomplete, so I'll guess as to what you are attempting to do.
I prefer to work with MVVM design Pattern, but here is a solution using tightly bound code behind.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadData();
}
private ObservableCollection<Subject> Subjects { get; } = new ObservableCollection<Subject>();
private void LoadData()
{
for (int i = 0; i < 10; i++)
{
Subjects.Add(new Subject
{
SubId = i,
SubName = "Name " + i,
SubStatus = "Status " + (10 - i)
});
}
SubjectDataGrid.ItemsSource = Subjects;
}
private void SubjectDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (SubjectDataGrid.SelectedItem != null)
{
var item = SubjectDataGrid.SelectedItem as Subject;
Id.Text = item.SubId.ToString();
Name.Text = item.SubName;
Status.Text = item.SubStatus;
}
else
{
Id.Text = "";
Name.Text = "";
Status.Text = "";
}
}
}
And here is the view:
<Window x:Class="DataGridSelectedItemCodeBehind.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DataGridSelectedItemCodeBehind"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<DataGrid Name="SubjectDataGrid"
SelectionChanged="SubjectDataGrid_OnSelectionChanged"/>
<Grid Column="1" VerticalAlignment="Center" Margin="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.Resources>
<Style TargetType="StackPanel">
<Setter Property="Orientation" Value="Horizontal"/>
</Style>
<Style TargetType="Label">
<Setter Property="Margin" Value="10"/>
<Setter Property="Width" Value="50"/>
</Style>
<Style TargetType="Border">
<Setter Property="Padding" Value="2"/>
<Setter Property="Margin" Value="0 4"/>
<Setter Property="Width" Value="200"/>
<Setter Property="BorderBrush" Value="Silver"/>
<Setter Property="BorderThickness" Value="2"/>
</Style>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</Grid.Resources>
<StackPanel>
<Label Content="ID:"/>
<Border>
<TextBlock Name="Id"/>
</Border>
</StackPanel>
<StackPanel Grid.Row="1">
<Label Content="Name:"/>
<Border>
<TextBlock Name="Name"/>
</Border>
</StackPanel>
<StackPanel Grid.Row="2">
<Label Content="Status:"/>
<Border>
<TextBlock Name="Status"/>
</Border>
</StackPanel>
</Grid>
</Grid>
</Window>