我有一份WPF申请。我正在尝试将FontSize和Background设置为DataGrid中的项目上的ToolTip。
I定义了以下XAML片段:
<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>我在"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:Path=TBackground;DataItem=null;目标元素为'ToolTip‘(名称=’‘);目标属性为’背景‘(键入'Brush') System.Windows.Data错误:4:无法找到引用“ElementName=MyWindow”绑定的源代码。BindingExpression:Path=TFontSize;DataItem=null;目标元素是'ToolTip‘(Name='');目标属性是'FontSize’(键入'Double')
我在这里错过了什么绑定过程?
谢谢
发布于 2017-04-11 08:49:50
TFontSize属性应该是double类型,并返回一个有效的字体大小> 0:
private double _tFontSize = 20;
public double TFontSize
{
get { return _tFontSize; }
set
{
_tFontSize = value;
NotifyPropertyChanged("TFontSize");
}
}然后,可以将DataGridCell的DataGridCell属性绑定到窗口,然后通过Tooltip的PlacementTarget属性将FontSize和Background属性绑定到窗口的源属性。
<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直接绑定到窗口。
https://stackoverflow.com/questions/43333767
复制相似问题