Houman
Houman

Reputation: 66320

How to bind a Tooltip's content to an MVVM property within code?

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>

Upvotes: 0

Views: 2992

Answers (1)

Steve Greatrex
Steve Greatrex

Reputation: 15999

You should be able to set up a binding as below:

BindingOperations.SetBinding(dataGridBoundColumn,
    ToolTipService.ToolTipProperty,
    new Binding("Path.To.My.Property"));

Note: the DataContext of this will be the value of the Header property on the column

You want to bind to a property on the view model; assuming that your view model is the DataContext for the DataGrid you would want to change the binding to something like:

new Binding("DataContext.ToolTipSorting")
{
    RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor)
    {
        AncestorType = typeof(DataGrid)
    }
}

This attempts to locate the first parent object of type DataGrid and grab the value of its DataContext.ToolTipSorting property.

Upvotes: 3

Related Questions