【发布时间】: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<>.Move,PointToScreen 可以正常工作。
我认为ObservableCollection<>.Move 在内部删除了该项目并将另一个项目插入到新位置。引发异常是因为 button 包含对已删除元素的引用,该元素实际上已与 TreeVisual 断开连接
【问题讨论】:
-
我现在看到您正在使用一个列表视图,我认为那是一个列表框,但它应该是相同的。
-
您在哪里使用该代码?我在
UserControl的测试事件处理程序中尝试了它,一切似乎都正常。 -
@Chris 我更新了问题。感谢您的评论。这让我想到:)
-
很高兴你找到了根本原因 =D
标签: c# wpf coordinates