问题
The answer I found at: How to rotate an image to a particular angle in Windows Phone 7 Silverlight Application? is close to what I am looking for.
My question is - how can I do this if the image is part of a style? The image is basically an arrow pointing in the direction of movement (track).
<Style x:Key="MyBoatPushPinStyle" TargetType="maps:Pushpin">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Image x:Name="MyBoatIcon"
Source="Resources/Icons/myboat.png"
Stretch="None">
<Image.RenderTransform>
<RotateTransform Angle="0" />
</Image.RenderTransform>
</Image>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The style is applied to a MapLayer:
<maps:MapLayer x:Name="LocationLayer">
<maps:Pushpin Style="{StaticResource MyBoatPushPinStyle}"
Location="{Binding CurrentLocation}" />
</maps:MapLayer>
What I can't figure is how to reference the image within the style, if that can actually be done.
Something like:
((RotateTransform)REFERENCE_TO_IMAGE.RenderTransform).Angle = _currentTrack;
回答1:
Try this:
<maps:MapLayer x:Name="LocationLayer">
<maps:Pushpin x:Name="PushpinLayer" Style="{StaticResource MyBoatPushPinStyle}" Location="{Binding CurrentLocation}" />
</maps:MapLayer>
Image a = FindFirstElementInVisualTree<Image>(PushpinLayer);
if (a != null)
((RotateTransform)a.RenderTransform).Angle = 90;
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
return (T)child;
else
{
var result = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
来源:https://stackoverflow.com/questions/9571842/rotate-a-style-image-on-windows-phone