Answered by:
within Canvas center a button

Question
-
hi, all friends!
I try to put a button in one Canvas, which Width and Height are dynamic, I'd like the button placed at the center of the Canvas, I failed. My code is the following:
<Canvas Name="VideoCanvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0" >
<MediaElement x:Name="videoPlayer"
PosterSource="{Binding PreviewImageURL}"
AutoPlay="False"
IsDoubleTapEnabled="True"
DoubleTapped="toggleFullScreen"
MediaOpened="videoPlayer_MediaOpened "
MediaEnded="videoPlayer_MediaEnded"
MediaFailed="videoPlayer_MediaFailed"
CurrentStateChanged="videoPlayer_CurrentStateChanged"
/>
<Button Name="PlayButton"
HorizontalAlignment="Center" VerticalAlignment="Center" Width="230" Height="230" BorderThickness="0" Visibility="Visible"
Click="Play_Button_Click"
>
<Image Source="Assets/MediaPlayer/play-video@2x.png" VerticalAlignment="Center" HorizontalAlignment="Center" Stretch="None"/>
</Button>
</Canvas>please help me!
Thursday, September 27, 2012 9:55 AM
Answers
-
HorizontalAlignment and VerticalAlignment will not work for a Canvas. They are applicable for Grid/StackPanel.
To place the button in the middle of a Canvas, set the Canvas.Left for the Button to (Canvas.Width - Button.Width)/2.
You'll have to calculate the Canvas.Top position using Height in the same way
- Proposed as answer by Dave SmitsMVP Thursday, September 27, 2012 7:58 PM
- Marked as answer by Min ZhuMember Monday, October 8, 2012 3:12 AM
Thursday, September 27, 2012 6:25 PM -
In code behind,
Canvas.SetLeft(PlayButton,(VideoCanvas.Width-PlayButton.Width)/2);
Canvas.SetTop(PlayButton,(VideoCanvas.Height-PlayButton.Height)/2);
- Marked as answer by Min ZhuMember Monday, October 8, 2012 3:12 AM
Friday, September 28, 2012 5:33 PM
All replies
-
HorizontalAlignment and VerticalAlignment will not work for a Canvas. They are applicable for Grid/StackPanel.
To place the button in the middle of a Canvas, set the Canvas.Left for the Button to (Canvas.Width - Button.Width)/2.
You'll have to calculate the Canvas.Top position using Height in the same way
- Proposed as answer by Dave SmitsMVP Thursday, September 27, 2012 7:58 PM
- Marked as answer by Min ZhuMember Monday, October 8, 2012 3:12 AM
Thursday, September 27, 2012 6:25 PM -
In fact, the Canvas.Width is dynamical, so I cannot set it in Xaml, how can I set it with behind Code C#? or how could I make a binding?Friday, September 28, 2012 9:51 AM
-
In code behind,
Canvas.SetLeft(PlayButton,(VideoCanvas.Width-PlayButton.Width)/2);
Canvas.SetTop(PlayButton,(VideoCanvas.Height-PlayButton.Height)/2);
- Marked as answer by Min ZhuMember Monday, October 8, 2012 3:12 AM
Friday, September 28, 2012 5:33 PM