캔바스 크기에 따라서 캔바스 안에 컨트롤을 중앙에 위치하도록 해보자
실행된 모습
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Com.Mariner.ERP.TestWPF" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="Com.Mariner.ERP.TestWPF.MainWindow"
Title="MainWindow" Height="405" Width="669" Loaded="Window_Loaded">
<Grid >
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="40.003"/>
</Grid.RowDefinitions>
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF373737" Offset="1"/>
<GradientStop Color="#FF878787"/>
</LinearGradientBrush>
</Grid.Background>
<Canvas ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" d:LayoutOverrides="Width" Name="CanvasMain">
<Canvas.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFCACACA" Offset="0"/>
<GradientStop Color="#FF6A6A6A" Offset="1"/>
</LinearGradientBrush>
</Canvas.Background>
<Rectangle Fill="#FFF4F4F5" Height="137" Canvas.Left="8" Stroke="Black" Width="266" Canvas.Top="6" Name="recItem" />
</Canvas>
<Button Content="check Size" HorizontalAlignment="Right" Margin="0,7.997,8,4.003" Width="123" Click="Button_Click" Grid.Row="1" />
<TextBox Height="28" HorizontalAlignment="Left" Margin="8,8,0,0" Name="textBox1" VerticalAlignment="Top" Width="492" Grid.Row="1" />
</Grid>
</Window>
CanvasMain.RenderSize //캔버스의 렌더링된 사이즈를 가져올수 있다.
비하인드 코드
private void Button_Click(object sender, RoutedEventArgs e)
{
SetSize(this.CanvasMain.RenderSize); //버튼클릭했을때 값을 확인해보자
}
private void SetSize(Size size)
{
double winl = (size.Width - this.recItem.ActualWidth) / 2; //가로크기에서 캔바스안에 아이템 넓이를 뺐따
double wint = (size.Height - this.recItem.ActualHeight) / 2;//가로크기에서 캔바스안에 아이템 높이를 뺐따
// Set new position of object.
recItem.SetValue(Canvas.TopProperty, wint);
recItem.SetValue(Canvas.LeftProperty, winl);
this.textBox1.Text = string.Format("Width: {0} Height: {1}", size.Width, size.Height);
}