C# – Fill TextBox from WPF DataGrid

cdatagridtextboxwpf

I have a WPF window with some text boxes and a DataGrid. The DataGrid gets filled with Data, but I need that, when the user clicks a cell in that DataGrid, the program detects the line and re-fills the text boxes with the data in that line.
For example, there is an ID, Name and BirthDate textbox. When the user clicks any cell in a given line, the text boxes ID, Name and BirthDate's values must become the values of their respective columns (ID, Name, BirthDate) in the line selected.
I've looked around for an answer to this, but I only seem to find answers relating to WinForms, and the DataGrid in WinForms and in WPF work quite differently, code-wise.

Best Answer

You can simply use Binding using the ElementName property to do this for you... no code behind needed:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <DataGrid Name="DataGrid" ItemsSource="{Binding YourDataCollection}" />
    <Grid Grid.Column="1">
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="{Binding SelectedItem.Id, 
            ElementName=DataGrid}" />
        <TextBlock Grid.Row="1" Text="{Binding SelectedItem.Name, 
            ElementName=DataGrid}" />
        <TextBlock Grid.Row="2" Text="{Binding SelectedItem.BirthDate, 
            ElementName=DataGrid}" />
    </Grid>
</Grid>