tk.
tk.

Reputation: 1216

wpf datagrid current item binding

I want to bind a content of a Label to the SelectedItem of a DataGrid.

I thought the 'current item' binding expression would work, but it does not.

My xaml code and code-behind c# is like below:

<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 of the DataTable, and does not change when I select other items on the DataGrid. It seems the current item of DataView does not change. What should I do to bind it to the current SelectedItem of the DataGrid?

Upvotes: 3

Views: 4981

Answers (2)

Johnny
Johnny

Reputation: 1575

Try this

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

Upvotes: 2

user7116
user7116

Reputation: 64068

The binding in your Label binds to Data independently of the DataGrid's binding to Data. Try:

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

Upvotes: 1

Related Questions