Grid中放入对象时,默认是居中的。如果对对象设置margin,对象应如何布局呢。
做一个实验。
结论:物体的左上角位置=(Grid容器宽度+物体左边距-物体宽度)/2 , (Grid容器高度+物体上边距-物体高度)/2

Code
<UserControl x:Class="MarginAlignment.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="400">
<Grid x:Name="LayoutRoot" Background="Wheat" MouseMove="LayoutRoot_MouseMove">
<Grid Width="100" Height="100" Background="Red" Margin="300,0,0,0"></Grid>
<StackPanel Margin="5,5,0,0" Orientation="Horizontal">
<TextBlock Name="label1">
光标位置:
</TextBlock>
<TextBlock Name="txt">(0,0)</TextBlock>
</StackPanel>
</Grid>
</UserControl>

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace MarginAlignment
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
private void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
{
this.txt.Text = string.Format("({0},{1})", e.GetPosition(this.LayoutRoot).X, e.GetPosition(this.LayoutRoot).Y); ;
}
}
}