【问题标题】:How to get the absolute screen coordinates of an element placed inside a DataTemplate如何获取放置在 DataTemplate 中的元素的绝对屏幕坐标
【发布时间】:2013-09-02 06:18:13
【问题描述】:

我有一个使用 UserControl 作为 DataTemplate 的 ListView:

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <views:TaskerInfoView />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

我需要放置在 TaskerInfoView 用户控件内的按钮的绝对屏幕坐标。

我尝试使用此代码:

var newButtonPoint = button.PointToScreen(new Point(0, 0));

但我收到了异常“此 Visual 未连接到 PresentationSource”,我想是因为该按钮位于 DataTemplate 内,因此它未连接到可视元素。

更新 我找到了收到该异常的原因:在调用 PointToScreen 之前,我将项目移动到 ObersvableCollection 中,即 ListView 的 ItemsSource:

this._taskList.Move(currentIndex, currentIndex - 1);  // _taskList is the ObservableCollection<>
var newButtonPoint = button.PointToScreen(new Point(0, 0));

如果我删除 ObservableCollection&lt;&gt;.Move,PointToScreen 可以正常工作。

我认为ObservableCollection&lt;&gt;.Move 在内部删除了该项目并将另一个项目插入到新位置。引发异常是因为 button 包含对已删除元素的引用,该元素实际上已与 TreeVisual 断开连接

【问题讨论】:

  • 我现在看到您正在使用一个列表视图,我认为那是一个列表框,但它应该是相同的。
  • 您在哪里使用该代码?我在UserControl 的测试事件处理程序中尝试了它,一切似乎都正常。
  • @Chris 我更新了问题。感谢您的评论。这让我想到:)
  • 很高兴你找到了根本原因 =D

标签: c# wpf coordinates


【解决方案1】:

例如:

xaml:

    <ListBox x:Name="myListBox" SelectedIndex="2">
        <ListBoxItem>1</ListBoxItem>
        <ListBoxItem>2</ListBoxItem>
        <ListBoxItem>3</ListBoxItem>
        <ListBoxItem>4</ListBoxItem>
        <ListBoxItem>5</ListBoxItem>
    </ListBox>

    <Button Content="GetIndexFromContainer" Click="Button_Click" />

cs:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var index = GetSelectedIndexFromList();
    }

    private int GetSelectedIndexFromList()
    {
        var container = myListBox.ItemContainerGenerator.ContainerFromItem(MyListBox.SelectedItem);
        var index = myListBox.ItemContainerGenerator.IndexFromContainer(container);
        return index;
    }

【讨论】:

  • 感谢您的回答,但我不需要列表中项目的相对位置。我更新/改进了问题;)
猜你喜欢
  • 2013-03-20
  • 2021-04-23
  • 2020-09-08
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 2015-08-01
  • 1970-01-01
相关资源
最近更新 更多