首页 文章

如何将WPF UserControl的DataGrid ToolTip FontSize绑定到我的主XAML窗口中定义的变量?

提问于
浏览
1

我've got a WPF Application. I' m试图在 DataGrid 中的项目上为 ToolTip 设置 FontSizeBackground .

I have the following XAML snippet defined:

<DataGridTextColumn Binding="{Binding Foo}"
                                Header="Foo"
                                Visibility="Visible"
                                Width="*">
   <DataGridTextColumn.CellStyle>
      <Style TargetType="DataGridCell">
         <Setter Property="ToolTip" >
            <Setter.Value>
               <ToolTip Background="{Binding ElementName=MyWindow,Path=TBackground}" 
                        FontSize="{Binding ElementName=MyWindow,Path=TFontSize}" >
                  <TextBlock Text="{Binding Foo}" />
               </ToolTip>
            </Setter.Value>
         </Setter>
      </Style>
   </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

I have the following defined in the code behind for "MyWindow"

private Brush _tBackground;
public Brush TBackground
{
   get { return _tBackground; }
   set
   {
      _tBackground = value;
      NotifyPropertyChanged("TBackground");
   }
}

private int _tFontSize;
public int TFontSize
{
   get { return _tFontSize; }
   set
   {
      _tFontSize = value;
      NotifyPropertyChanged("TFontSize");
   }
}

在运行时,我收到以下错误:

System.Windows.Data错误:4:无法找到引用'ElementName = MyWindow'的绑定源 . BindingExpression:路径= TBackground;的DataItem = NULL; target元素是'ToolTip'(Name ='');目标属性是'背景'(类型'刷'')System.Windows.Data错误:4:无法找到引用'ElementName = MyWindow'的绑定源 . BindingExpression:路径= TFontSize;的DataItem = NULL; target元素是'ToolTip'(Name =''); target属性是'FontSize'(类型'Double')

我在这里错过了哪些绑定过程?

谢谢

1 回答

  • 1

    TFontSize 属性的类型应为 double ,并返回有效的字体大小> 0:

    private double _tFontSize = 20;
    public double TFontSize
    {
        get { return _tFontSize; }
        set
        {
            _tFontSize = value;
            NotifyPropertyChanged("TFontSize");
        }
    }
    

    然后,您可以将 DataGridCellTag 属性绑定到窗口,然后通过 TooltipPlacementTarget 属性将 FontSizeBackground 属性绑定到窗口的源属性:

    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=Window}}" />
            <Setter Property="ToolTip" >
                <Setter.Value>
                    <ToolTip
                        Background="{Binding Path=PlacementTarget.Tag.TBackground, RelativeSource={RelativeSource Self}}"
                        FontSize="{Binding Path=PlacementTarget.Tag.TFontSize, RelativeSource={RelativeSource Self}}" >
                        <TextBlock Text="{Binding Foo}" />
                    </ToolTip>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGridTextColumn.CellStyle>
    

    因为 Tooltip 位于其自己的可视树中,所以无法使用 ElementName 直接绑定到窗口 .

相关问题