1

How can I access the Image from codebehind from TextBlock for the following XAML?

<TextBlock Name="btnRating5" PreviewMouseDown="btnRating5_PreviewMouseDown"
           Tag="{Binding ID}" Margin="5,0,0,0" Padding="1">
<Image Source="{Binding Rating, Mode=OneTime, Converter={StaticResource MyImagePathConverter}}" />
</TextBlock>
1
  • Why do you need to "access" that UI element? It's already DataBound to an underlying data item. Whatever you need to do should be done via DataBinding rather than procedural code.
    – Fede
    Jul 29, 2014 at 0:20

1 Answer 1

2

You can use VisualTreeHelper class to get the child of any control.

Suppose you want to find the image in PreviewMouseDown event of TextBlock then you can do it like this :

private void btnRating5_PreviewKeyDown(object sender, ....... e)
{
    var containerVisual = VisualTreeHelper.GetChild((TextBlock)sender, 0) as ContainerVisual;
    Image myImage = containerVisual .Children[0] as Image;
}

If the code does not work then try to change the index from 0 to 1.

Let me know if you have any problems :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.