Binding the current wpf datagrid element

I want to associate content Labelwith SelectedItem DataGrid.

I thought that the binding expression of the current element would work, but it is not.

My xaml code and C # code is as follows:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="512" Width="847">
    <DockPanel LastChildFill="True">
        <Label Content="{Binding Data/colA}" DockPanel.Dock="Top" Height="30"/>
        <DataGrid ItemsSource="{Binding Data}"></DataGrid>
    </DockPanel>
</Window>

namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MyData();
        }
    }

    public class MyData
    {
        DataTable data;
        public MyData()
        {
            data = new DataTable();
            data.Columns.Add("colA");
            data.Columns.Add("colB");
            data.Rows.Add("aa", 1);
            data.Rows.Add("bb", 2);
        }
        public DataTable Data { get { return data; } }
    }
}

The label shows the first item DataTableand does not change when I select the other items in DataGrid. It seems the current item is DataViewnot changing. What needs to be done to bind it to the current SelectedItem DataGrid?

+3
source share
2 answers

The binding in Labelsits to Dataregardless of the binding DataGridto Data. Try:

<Label Content="{Binding SelectedValue, ElementName=TheGrid}" />
<DataGrid x:Name="TheGrid" ItemsSource="{Binding Data}" />
+1
source

<Label Content = "{Binding ElementName = DataGridName, Path = SelectedItem}"/>
+2

Source: https://habr.com/ru/post/1746435/


All Articles