WPF - How could I get a scrollviewer control from my XAML file in C#?

你离开我真会死。 提交于 2020-03-06 02:34:08

问题


I need to get a specific ScrollViewer control from an XAML file in C#, so that I can try to implement a drag-and-scroll system where when an item is dragged near the edge it will scroll accordingly. But I need access to all the methods to do this, yet I cannot find any info as to how to get the specific scrollviewer from the XAML.

I need access to it from a separate .cs file in which most of the project's converters and functions are located. Not sure bout the downvotes tho seeing as I did lots of research on it. Here is some of the code:

<ScrollViewer  x:Name="timelineScrollerRight" Grid.Row="1" VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Disabled" PreviewMouseWheel="TimelineScrollerRightMouseWheel">

That is the ScrollViewer tag that I want to access. I want to change the LineRight/LineLeft attributes of the ScrollViewer in a MouseMove event triggered by another control within the ScrollViewer.

The C# code is bare right now, the event is empty, I want to be able to declare a variable to allow me to change the ScrollViewer attributes so that when the MouseMove event is called, the ScrollViewer is scrolled and so on. The ScrollViewer is located in a file named TimelineAnimationView.xaml and the event happens in the code-behind, TimelineAnimationView.xaml.cs. But I would also like to access it from a separate .cs file if needed.


回答1:


Normally you access it using x:Name:

<ScrollViewer x:Name="scoller"/>

If you are doing this with loose XAML such as in a UserControl or Window, you just access it as a private instance variable scroller in your code-behind.

If you are doing this with a ScrollViewer in a template, then you have to use GetTemplateChild (in OnApplyTemplate) to find the child type with the relevant name:

scroller = GetTemplateChild("scroller");


来源:https://stackoverflow.com/questions/28840705/wpf-how-could-i-get-a-scrollviewer-control-from-my-xaml-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!