【问题标题】:WPF - Getting position of a control keeps returning {0;0}WPF - 获取控件的位置不断返回 {0;0}
【发布时间】:2018-11-13 13:13:28
【问题描述】:

我正在尝试获取控件(按钮)的位置,但它一直返回 {0;0}。我确信对此有解释,但我无法弄清楚为什么会发生这种情况。

我想要控件的位置,相对于窗口或某个容器。我的按钮排列在另一个网格中。获取这些按钮的边距只会给出 0,0,因为它们都在网格单元格内。

我尝试了什么:

- var point = btnTest.TransformToAncestor(mainGrid).Transform(new Point());
- UIElement container = VisualTreeHelper.GetParent(btnTest) as UIElement;
  Point relativeLocation = btnTest.TranslatePoint(new Point(0, 0), mainGrid);

我用一个网格作为父级和一个画布尝试了这个。我尝试的一切都给了我{0,0}。当我更改 new Point 参数时,位置确实发生了变化。它与参数保持相同。

我的 XAML 的一小部分:

    <Grid x:Name="mainGrid">
    <Grid Name="buttonGrid" Margin="105,64,98.4,97.8">
        <Grid.RowDefinitions>
            <RowDefinition Height="25"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="25"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50"/>
            <ColumnDefinition Width="50"/>
            <ColumnDefinition Width="50"/>
        </Grid.ColumnDefinitions>
        <Button x:Name="btnTest" Grid.Row="0" Grid.Column="0" Content="Button" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="26" Height="29"/>
        <Button x:Name="btnTest2" Grid.Row="1" Grid.Column="1" Content="Button" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="26" Height="29"/>
    </Grid>
</Grid>

【问题讨论】:

  • 你应该发一个MVCE,这样更容易帮助你。这包括删除不必要的东西和实际上包括相关的东西(例如,btnTest 在你的 XAML 中找不到)。
  • 感谢您的反馈。我已经编辑了我的问题。
  • Button 相对于 mainGrid 的位置是 0,0,不是吗?
  • @mm8 正如您在 Margin 中看到的那样,我将按钮拖到屏幕中间。不过,这个位置是 0,0。我相信对此有一个解释,我只是不明白为什么。

标签: c# wpf position


【解决方案1】:

您的代码运行良好,问题在于时间。必须先绘制 UI 元素,然后才能检索位置。

下面的代码示例显示了在构造函数中运行的点提取,结果为 0,0,然后在返回所需结果 84,78 的加载事件中运行。

<Window x:Class="WpfApp7.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Grid x:Name="mainGrid">
    <Button x:Name="btnTest" Content="TileButton" HorizontalAlignment="Left" Margin="84,78,0,0" VerticalAlignment="Top" Width="109" Height="103"/>
</Grid>

 public MainWindow()
    {
        InitializeComponent();
        GetPoint();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        GetPoint();
    }

    private void GetPoint()
    {
        var point = btnTest.TransformToAncestor(mainGrid).Transform(new Point());
        UIElement container = VisualTreeHelper.GetParent(btnTest) as UIElement;
        Point relativeLocation = btnTest.TranslatePoint(new Point(0, 0), mainGrid);
        MessageBox.Show($"X = {relativeLocation.X} Y = {relativeLocation.Y}");
    }        

【讨论】:

  • 谢谢!我不敢相信我已经为这个简单的解决方案寻找了 2 天!
猜你喜欢
  • 2016-09-23
  • 2014-11-06
  • 2021-02-14
  • 2012-10-26
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多