c# - WPF - 获取控件的位置不断返回 {0;0}

标签 c# wpf position

我正在尝试获取控件(按钮)的位置,但它一直返回 {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);

我用网格作为父级并用 Canvas 尝试了这个。我尝试的一切都给我 {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>

最佳答案

您的代码运行良好,问题在于时机。必须先绘制 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}");
    }        

关于c# - WPF - 获取控件的位置不断返回 {0;0},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50676549/

相关文章:

c# - 在 WPF 中使用 ToolBarTray 控件进行数据绑定(bind)

c# - 使用 MessageBox.Show() 阻止所有窗口

c# - WPF .NET Core 3.1 应用程序发布单个文件(发布)失败

html - 下拉样式停留在顶部不起作用

c# - 自定义从 Web API 接收的 JSON

c# - 当图像是位图时,使用 Graphics.DrawImage(Image, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit) 有好处吗?

jquery - 同时并行多个 jQuery-Effects

Android 检查位置 View

c# - 单击按钮时如何从列表框和 ObservableCollection 中删除自定义项

c# - 处理包含 "question mark"(�) 的字符串时出现编码问题