tags:

views:

238

answers:

2

I want to bind a content of a label to the selected item of a datagrid.

I thought the 'current item' binding expression would work, but it is 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 selected item of datagrid?

+1  A: 

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}" />
sixlettervariables
A: 

Try this

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