Get selected row item in DataGrid WPF

You can use the SelectedItem property to get the currently selected object, which you can then cast into the correct type. For instance, if your DataGrid is bound to a collection of Customer objects you could do this: Customer customer = (Customer)myDataGrid.SelectedItem; Alternatively you can bind SelectedItem to your source class or ViewModel. <Grid DataContext=”MyViewModel”> … Read more

WPF Error: Cannot find governing FrameworkElement for target element

Sadly any DataGridColumn hosted under DataGrid.Columns is not part of Visual tree and therefore not connected to the data context of the datagrid. So bindings do not work with their properties such as Visibility or Header etc (although these properties are valid dependency properties!). Now you may wonder how is that possible? Isn’t their Binding … Read more

How do I bind a WPF DataGrid to a variable number of columns?

Here’s a workaround for Binding Columns in the DataGrid. Since the Columns property is ReadOnly, like everyone noticed, I made an Attached Property called BindableColumns which updates the Columns in the DataGrid everytime the collection changes through the CollectionChanged event. If we have this Collection of DataGridColumn’s public ObservableCollection<DataGridColumn> ColumnCollection { get; private set; } … Read more

How to get ToolTip from WPF Data Grid Column Header (DataGridTemplateColumn) in code?

Put the TextBlock in the HeaderTemplate of the column: <DataGridTemplateColumn x:Name=”col”> <DataGridTemplateColumn.HeaderTemplate> <DataTemplate> <TextBlock Text=”Current” ToolTip=”Price” ToolTipService.InitialShowDelay=”0″ ToolTipService.Placement=”Top” ToolTipService.ShowDuration=”999999″ RenderOptions.BitmapScalingMode=”NearestNeighbor”/> </DataTemplate> </DataGridTemplateColumn.HeaderTemplate> </DataGridTemplateColumn> …and find it in using the VisualTreeHelper: private void Button_Click(object sender, RoutedEventArgs e) { var columns = FindVisualChildren<System.Windows.Controls.Primitives.DataGridColumnHeader>(dataGrid)? .ToArray(); if (columns != null) { int columnIndex = 1; if (columns.Length > columnIndex) … Read more