您的位置:首页 > 其它

Silverlight 2 RTW中ToolTipService.ToolTip不继承父节点的DataContext的问题

2009-04-12 22:11 232 查看
在Silverlight2 RTW中,利用ToolTipService.ToolTip可以实现ToolTip(提示)效果,例如:

<Button Width="100" Height="40" Content="Button" ToolTipService.ToolTip="这是提示信息

" />
显示如图:



我们还可以自定义提示信息的显示样式,例如改变字体或者显示复杂的图形,等等。例如:

<Button Width="100" Height="40" Content="Button">
<ToolTipService.ToolTip>
<Grid>
<Ellipse Width="150" Height="50" Fill="Beige"></Ellipse>
<TextBlock Text="这是提示信息

" Foreground="Red" />
</Grid>
</ToolTipService.ToolTip>
</Button>

显示如图:



对于提示信息,同样可以使用Binding(特别是在ControlTemplate里常常使用Binding,例如ListBoxItem)。例如:

<Grid DataContext="{StaticResource MyUser}">
<Button Width="100" Height="40" Content="Button" ToolTipService.ToolTip="{Binding UserName}" />
</Grid>
但下面的这种绑定方式确不能正常显示提示信息:

<Grid DataContext="{StaticResource MyUser}">
<Button Width="100" Height="40" Content="Button">
<ToolTipService.ToolTip>
<TextBlock x:Name="txt" Text="{Binding UserName}" />
</ToolTipService.ToolTip>
</Button>
</Grid>

这是因为在Silverlight 2RTW里,ToolTipService.ToolTip没有继承上层元素的DataContext。如果我们显示指定ToolTipService.ToolTip的DataContext,这种方式同样可以工作。但显示指定ToolTip的DataContext在有的场合是有点别扭,特别是在ControlTemplate里更是有一定的困难。
为了使ToolTip能够利用父级的DataContext进行绑定,在http://silverlight.net/forums/p/14241/46745.aspx#46745讨论了在Beta 1下修改ToolTip原代码的方法。目前我还没有找到Silverlight 2 RTW下对应的Controls完整示例代码,为此,我们可以用一个变通的方式来绕过这个问题。既然直接在ToolTipService.ToolTip="{Binding UserName}" 里能够成功绑定,为了实现复杂的提示信息,我们可以借助Converter来实现:

<UserControl.Resources>
<local:Converter x:Name="myConverter" />
</UserControl.Resources>

<Grid DataContext="{StaticResource MyUser}">
<Button Width="100" Height="40" Content="Button" ToolTipService.ToolTip="{Binding UserName,Converter={StaticResource myConverter}}" />
</Grid>

关键的部分我们在Converter里实现:

public class Converter : IValueConverter
{
#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
var s = value.ToString();
TextBlock block = new TextBlock();
block.Text = s;
block.Style = (Style)Application.Current.Resources["MyTextBlockStyle"];
return block;
}
return null;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
可以参考这个帖子:http://silverlight.net/forums/p/84675/197144.aspx#197144
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: