views:

278

answers:

1

Silverlight provides element to element binding. How to apply it this is case:

I have a xaml as below:

<TextBlock Text="{Binding ABC}" >
  <ToolTipService.ToolTip>
    <local:MyControl Title="{Binding ...}" />
  </ToolTipService.ToolTip>
</TextBlock>

I want to bind MyControl Title to the same data as its parent Textblock Text, but I don't want set x:Name for its parent Textblock.

I know there is one solution to bind Title to same data source:

<local:MyControl Title="{Binding ABC}" />

This may cause two times to call "{Binding ABC}", with my case, there ValurConverter for this binding. I don't want to use this way.

A: 

Try binding by specifying a relative source:

{Binding RelativeSource={RelativeSource
FindAncestor, AncestorType={x:Type
TextBlock}}}

This should bind to the first "TextBlock" type preceding MyControl.

UPDATE: The FindAncestor RelativeSource currently (as of Dec. 8, 2009) only works in WPF, NOT Silverlight.

But there is an request open (8/3/2009) with the Silverlight team to bring FindAncestor into a future version of Silverlight: Link

Microsoft's word on this subject:

We are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com) (8/4/2009)


Currently the best options you may have are listed here: Link

As shown you can enclose your MyControl within a TextBox Template. Then you can bind title using the following code:

{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text}

Hope this helps.

Alex
I was just testing the same thing before posting it and weirdly it doesn't work - as if the tooltip is not a descendant of the textblock.
Andrew
Thank you. Above syntax give me following error:The property 'AncestorType' does not exist on the type 'RelativeSource' in the XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'. The tag 'Type' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml'.
KentZhou

related questions