【问题标题】:How to bind a Tooltip's content to an MVVM property within code?如何将 Tooltip 的内容绑定到代码中的 MVVM 属性?
【发布时间】:2011-11-09 17:01:12
【问题描述】:

由于我们软件的性质,我们必须在后面的代码中动态创建我们的数据网格列,然后将其添加到数据网格中,如下所示:

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

现在我们需要在列标题上添加一个工具提示:

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

那也很好用。但是,我需要将工具提示的值绑定到 ViewModel 上的属性。我知道如何在 xaml 中执行此操作,但不知道如何在代码中执行此操作。

任何帮助将不胜感激,

更新:

感谢史蒂夫的回答,我能够稍微不同地解决这个问题:

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>

【问题讨论】:

    标签: c# .net wpf silverlight


    【解决方案1】:

    您应该能够设置如下绑定:

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

    注意:这里的DataContext 将是列上Header 属性的值

    你想绑定到视图模型上的一个属性;假设您的视图模型是 DataContext 的 DataGrid,您可能希望将绑定更改为:

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

    这会尝试定位DataGrid 类型的第一个父对象并获取其DataContext.ToolTipSorting 属性的值。

    【讨论】:

    • 谢谢史蒂夫。我得到 System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。 BindingExpression:Path=ToolTipSorting;数据项=空;目标元素是“DataGridTextColumn”(HashCode=42996073);目标属性是“工具提示”(类型“对象”)
    • 如果 Datacontext 在 Header 上,请问如何绑定到 ViewModel 上的 MVVM 属性“ToolTipSorting”?
    • 我不能 100% 确定 DataContext 将是 Header 属性 - 您可以将绑定路径留空以查看示例中数据上下文的类型吗?
    • 对不起,忽略我的最后一条评论 - 被误解了。查看我的更新
    • 非常感谢史蒂夫。它并没有完全那样工作,但你给了我正确的方向。我已经编辑了我的问题,因为我必须进行一些小改动才能使其发挥作用。再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2011-05-20
    • 2014-09-29
    • 1970-01-01
    相关资源
    最近更新 更多