wpf datagrid current item binding

Posted by tk on Stack Overflow See other posts from Stack Overflow or by tk
Published on 2010-05-20T17:37:35Z Indexed on 2010/05/20 17:40 UTC
Read the original article Hit count: 683

Filed under:
|
|

I want to bind a content of 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?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about c#