WPF Styles and Tooltips Question
I have a style that I am using to make dynamic tooltips on certain text boxes like so.
<Style TargetType="{x:Type TextBox}">
<Setter Property="MinWidth" Value="100"/>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<!-- item of interest -->
<Setter Property="ToolTip">
<Setter.Value>
<MultiBinding Converter="{StaticResource ErrorMessageConverter}">
<Binding RelativeSource="{RelativeSource Self}" Path="Tag"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
This works very well, but if I want to use a more complex tooltip I can't figure out how to bind to 'Tag' anymore for t开发者_JAVA技巧he converter value. For example;
...
<Setter Property="ToolTip">
<Setter.Value>
<StackPanel>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource ErrorMessageConverter}">
<!-- item of interest -->
<Binding RelativeSource=" what goes here?? "/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
<Image/>
</StackPanel>
</Setter.Value>
</Setter>
...
I have tried several flavors of 'FindAncestor' and what not for the relative source, but I can't get anything to work. Any ideas??
UPDATE: 12-29-2010 : Here is the correct code, answer provided by our friend Goblin below. Works perfectly!
...
<Setter Property="ToolTip">
<Setter.Value>
<!-- Item of interest -->
<ToolTip DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
<StackPanel>
<Image/>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource ErrorMessageConverter}">
<Binding Path="Tag"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</ToolTip>
</Setter.Value>
</Setter>
...
See Karl Shifflett for the full explanation of how to inherit the DataContext of the 'owning' control from the ToolTip: http://karlshifflett.wordpress.com/2007/12/29/wpf-sample-series-data-binding-in-tooltip/
It isn't exactly Textbook stuff :)
The problem is that ToolTips are popups that exist outside of the main visual tree, which causes both RelativeSource and ElementName to break when looking for elements outside the ToolTip. The easiest way around this is to use the inherited DataContext for your Bindings as that is passed through to the ToolTip, but this doesn't always give access to what you need.
An alternative is to use a custom Attached Property declared with FrameworkMetadataOptions.Inherits. You can then set a value for that property on the owner object (TextBox in this case) and then access the inherited value on any element inside the ToolTip. In this case you would set the Attached Property value instead of the Tag.
Try using x:Name
on the control with the tooltip, and then <Binding ElementName="yourName" Path="Tag">
for the binding.
精彩评论