如何在代码中将Tooltip's内容绑定到MVVM属性

本文关键字:绑定 属性 MVVM 代码 Tooltip | 更新日期: 2023-09-27 18:14:03

由于我们的软件的性质,我们必须在代码中动态地创建我们的数据网格列,然后像这样将它添加到数据网格中:

DataGridBoundColumn dataGridBoundColumn = new DataGridTextColumn
                                                          {
                                                              CellStyle = ...,                                                                            
                                                              Header = header,
                                                              Binding = binding
                                                          };
reportDataGrid.Columns.Add(dataGridBoundColumn);

现在我们需要一个columnheader的工具提示:

ToolTipService.SetToolTip(dataGridBoundColumn, "ENTER VALUE");

这也很好。然而,我需要将工具提示的值绑定到ViewModel上的一个属性。我知道如何在xaml中这样做,但不知道如何在代码中做到这一点。

任何帮助都将不胜感激,

更新:

感谢Steve的回答,我能够稍微改变这个问题:

Binding bindingBoundToTooltipProperty = new Binding()
                                   {
                                       Source = reportDataGrid.DataContext, 
                                       Path = new PropertyPath("ToolTipSorting")
                                   };

BindingOperations.SetBinding(dataGridBoundColumn, ToolTipService.ToolTipProperty, bindingBoundToTooltipProperty);

如果DataGridColumnHeaderStyle是自定义的,请确保将这些行也添加到模板中:

<Trigger Property="IsMouseOver" Value="True">
    <Setter Property="ToolTip" Value="{Binding Column.(ToolTipService.ToolTip), RelativeSource={RelativeSource Self}}"/>
</Trigger>

如何在代码中将Tooltip's内容绑定到MVVM属性

您应该能够像下面这样设置绑定:

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

注意:DataContext将是列

上的Header属性的值。

你想绑定到视图模型上的属性;假设您的视图模型是DataGridDataContext,您希望将绑定更改为以下内容:

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

这将尝试找到DataGrid类型的第一个父对象,并获取其DataContext.ToolTipSorting属性的值。