如何在XAML中获取控件的位置?

时间:2016-04-07 08:04:31

标签: wpf xaml

我想获得一个控件相对于其父级的位置,或者只是任何一种位置,并不重要。但我想只在XAML中做这个,没有任何代码。我有一个网格5x3,按钮位于第3行和第2列。所以,基本上我想得到网格的前两行的宽度,以及网格的第一列的宽度。

我想知道按钮的位置(以像素为单位),因为我想做这样的翻译动画:

<DoubleAnimation Storyboard.TargetName="Studio" Storyboard.TargetProperty="RenderTransform.(TranslateTransform.X)" From="500" To="0" Duration="0:0:2"> 

但是我没有使用500的硬编码值,而是希望它与按钮的水平位置(以像素为单位)相对应

1 个答案:

答案 0 :(得分:2)

Something like the XAML below might work for you. It is inspired by your idea of a transparent dummy Rectangle that fills the columns left of the Button.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <Rectangle x:Name="dummy" Grid.ColumnSpan="2"/>

    <Button Grid.Column="2" VerticalAlignment="Center" Content="Click">
        <Button.RenderTransform>
            <TransformGroup>
                <ScaleTransform ScaleX="-1"/>
                <TranslateTransform/>
                <ScaleTransform ScaleX="-1"/>
            </TransformGroup>
        </Button.RenderTransform>
        <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation
                            Storyboard.TargetProperty="RenderTransform.Children[1].X"
                            To="{Binding ActualWidth, ElementName=dummy}"
                            Duration="0:0:2"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Button.Triggers>
    </Button>
</Grid>

Instead of declaring the RenderTransform as shown above you may perhaps better use a binding converter to invert the value of the dummy Rectangle's ActualWidth property.