如何将WPF ScrollViewer的内容滚动到特定位置
我正在编写自定义 WPF ItemsControl 来显示项目列表。这些项目显示为嵌入在 ScrollViewer 中:
<Style TargetType="MyCustomItemsControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="MyCustomItemsControl">
<ScrollViewer x:Name="PART_MyScrollViewer" >
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我想确保当我将鼠标移动到控件中时,特定项目(标记为选定)将滚动到鼠标位置。在我的 OnMouseEnter 方法中,我能够找到该项目,但我不知道下一步该做什么。有人知道吗?
protected override void OnMouseEnter(MouseEventArgs e)
{
for (int i = 0; i < Items.Count; i++)
{
ContentPresenter uiElement = (ContentPresenter)ItemContainerGenerator.ContainerFromIndex(i);
var item = uiElement.Content as MyCustomObject;
if (item.IsSelected)
{
// How to scroll the uiElement to the mouse position?
break;
}
}
}
I am writing my custom WPF ItemsControl to display a list of item. The items are shown embedded inside a ScrollViewer:
<Style TargetType="MyCustomItemsControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="MyCustomItemsControl">
<ScrollViewer x:Name="PART_MyScrollViewer" >
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I want to make sure that when I move the mouse into the control, a particular item (marked as selected) will be scrolled into the mouse position. In my OnMouseEnter method I am able to find the item but I don't know what to do next. Does anyone have any idea?
protected override void OnMouseEnter(MouseEventArgs e)
{
for (int i = 0; i < Items.Count; i++)
{
ContentPresenter uiElement = (ContentPresenter)ItemContainerGenerator.ContainerFromIndex(i);
var item = uiElement.Content as MyCustomObject;
if (item.IsSelected)
{
// How to scroll the uiElement to the mouse position?
break;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
参考: https://msdn.microsoft.com/en-us/library/ms598110 .aspx
更新:(感谢@jmbpiano)注意,它不会将控件精确地带到当前鼠标光标位置。它只是将控件带到可见的位置,操作员可以在其中用鼠标单击它(在 99% 的情况下,发现此问题的人可能需要这样做)。
REF: https://msdn.microsoft.com/en-us/library/ms598110.aspx
UPDATE: (thanks to @jmbpiano) Note, it does not bring the control exactly to the current mouse cursor position. It just brings the control to a visible position, where the Operator will be able to click it with the mouse (which in 99% of cases is all someone who finds this question is likely to need).
像下面这样:
Something like the following:
使用 UIElement.TranslatePoint() 计算要滚动到的位置
使用 ScrollViewer.ScrollToVerticalOffset() 进行滚动
Use UIElement.TranslatePoint() to calculate what position you want to scroll to
Use ScrollViewer.ScrollToVerticalOffset() to do the scrolling
试试下面的代码:
Try this below code :