Due the nature of our software, we have to create our datagrid columns dynamically in code behind and add it then to the datagrid like this:
DataGridBoundColumn dataGridBoundColumn = new DataGridTextColumn
{
CellStyle = ...,
Header = header,
Binding = binding
};
reportDataGrid.Columns.Add(dataGridBoundColumn);
Now we need a tooltip on the columnheader:
ToolTipService.SetToolTip(dataGridBoundColumn, "ENTER VALUE");
Well that works fine too. However I need to bind the tooltip’s value to a property on the ViewModel. I know how to do this in the xaml, but no idea how to do that in code.
Any help would be appreciated,
UPDATE:
Thanks to Steve’s answer I was able to fix this slightly differently:
Binding bindingBoundToTooltipProperty = new Binding()
{
Source = reportDataGrid.DataContext,
Path = new PropertyPath("ToolTipSorting")
};
BindingOperations.SetBinding(dataGridBoundColumn, ToolTipService.ToolTipProperty, bindingBoundToTooltipProperty);
if the DataGridColumnHeaderStyle was customized, make sure to add these lines to the template as well:
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="ToolTip" Value="{Binding Column.(ToolTipService.ToolTip), RelativeSource={RelativeSource Self}}"/>
</Trigger>
You should be able to set up a binding as below:
Note: the
DataContextof this will be the value of theHeaderproperty on the columnYou want to bind to a property on the view model; assuming that your view model is the
DataContextfor theDataGridyou would want to change the binding to something like:This attempts to locate the first parent object of type
DataGridand grab the value of itsDataContext.ToolTipSortingproperty.