Uwp ListView list sliding effect, uwplistview

Source: Internet
Author: User

Uwp ListView list sliding effect, uwplistview

I have read an article

WPF custom control list sliding effect PowerListBox http://www.cnblogs.com/ShenNan/p/4993374.html#3619585 to achieve the sliding effect (that is, animation), I think it is very interesting to achieve in UWP. The best results are as follows:

Next let's talk about how it is implemented:

1. Add Behaviors

Right-click the project and select "manage NuGet packages"

Search for Behaviors to add

 

2. Add a new class

This class is called

ListViewBehavior 

Inherit DependencyObject, inherit the IBehavior interface, and then display the two methods that inherit this interface

  public class ListViewBehavior : DependencyObject, IBehavior    {        public DependencyObject AssociatedObject { get; set; }        public void Attach(DependencyObject associatedObject)        {            throw new NotImplementedException();        }        public void Detach()        {            throw new NotImplementedException();        }    }

Then add some attributes to this class, which will be used later.

Public DependencyObject AssociatedObject {get; set ;}/// <summary> /// list of public ListView to be animated /// </summary>; /// <summary> /// the scroll bar in the listView /// </summary> public ScrollViewer scroll;

/// <Summary>
/// Container layout direction
/// </Summary>
Private Orientation _ panelOrientation;


/// <Summary> /// the first item in the current visualization view /// </summary> private int firstVisibleIndex; /// <summary> /// the last entry of the current Visual View /// </summary> private int lastVisibleIndex; /// <summary> /// the first item of the visualization view during the last rolling // </summary> private int oldFirstVisibleIndex; /// <summary> /// last item of the visualization view during the last rolling // </summary> private int oldLastVisibleIndex; // <summary> // ID, whether the first Item is found /// </summary> private bool isFindFirst; // <summary> // The value of the height or width of the Item that has been traversed in total, used to find the first and last items // </summary> private double cumulativeNum; public void Attach (DependencyObject associatedObject) {} public void Detach (){}

The attributes are ready. Now let's proceed to the official future. Add the code in the Attach method.

Public void Attach (DependencyObject associatedObject) {// obtain the ListView list object ListView = associatedObject as ListView; if (ListView = null) {return ;} // If the passed object is not empty, we will register an event ListView for this object. loaded + = ListView_Loaded ;}

ListView_Lodaded code:

/// <Summary> /// logic code after the list object is loaded /// </summary> /// <param name = "sender"> </param>/ // <param name = "e"> </param> private void ListView_Loaded (object sender, routedEventArgs e) {// find the rolling view and assign the value to the attributes we just added. scroll = FindVisualChild <ScrollViewer> (ListView, "ScrollViewer"); // you can check whether the view is empty, if it is not null, add an event if (scroll = null) {return;} else {// listen to the scroll event. viewChanged + = Scroll_ViewChanged ;}

ItemsPresenter v = FindVisualChild <ItemsPresenter> (ListView ,"");

 

ItemsStackPanel items = FindVisualChild <ItemsStackPanel> (v ,"");

 

_ PanelOrientation = items. Orientation;

        }
/// <Summary> /// obtain the template control /// </summary> /// <typeparam name = "T"> type </typeparam> /// <param name = "obj"> control object </param> // <returns> </returns> protected T FindVisualChild <T> (DependencyObject obj, string name) where T: DependencyObject {// obtain the number of sub-objects in the control visualization tree int count = VisualTreeHelper. getChildrenCount (obj); // traverses each object based on the index for (int I = 0; I <count; I ++) {var child = VisualTreeHelper. getChild (obj, I ); // Determine whether the object we are looking for is based on the parameter. If yes, return and exit the method, // if not, recursively go to the next layer to find if (child is T & (FrameworkElement) child ). name = name) {return (T) child;} else {var child1 = FindVisualChild <T> (child, name); if (child1! = Null) {return (T) child1 ;}} return null ;}

 

Now that you have obtained the ScrollViewer object in the list, you can execute the core part of this animation. By listening to the rolling event, you can obtain the control for animation.

/// <Summary> /// listen for Rolling events /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private void Scroll_ViewChanged (object sender, scrollViewerViewChangedEventArgs e) {// calculate the first and last CalculationIndex () of the current visualization area each time you scroll ();}

Add two more fields

/// <Summary> /// list the height of the Child control /// </summary> private double itemsHeight; // The translation effect object private TranslateTransform tt;
/// <Summary> /// calculate the first and last items of the visualization area /// </summary> private void CalculationIndex () {// assign the value to the old first visualization view oldFirstVisibleIndex = firstVisibleIndex; // assign the value to the last visualization view oldLastVisibleIndex = lastVisibleIndex; // mark whether isFindFirst = false is found for the first item; // determine the direction of the list if (_ panelOrientation = Orientation. vertical) {cumulativeNum = 0.0; // traverses all the visual views of the list and searches for the first and last for (int I = 0; I <ListView. items. count; I ++) {// convert to ListViewI Tem object used to operate var _ item = ListView. containerFromIndex (I) as ListViewItem; // There is a pitfall here, So ListView supports virtualization. Therefore, only about 20 items can be obtained each time, therefore, we need to record the height and accumulate the height of the retrieved // Visual View. If (_ item = null) {cumulativeNum + = itemsHeight;} else {itemsHeight = _ item. actualHeight; cumulativeNum + = _ item. actualHeight + _ item. margin. top + _ item. margin. bottom;} // determine whether the current accumulated height is greater than the distance we scroll to find the first if (! IsFindFirst & cumulativeNum> = scroll. verticalOffset) {// record the first item's claim firstVisibleIndex = I; // indicates that the first item has found isFindFirst = true; Up ();} // The currently accumulated height is greater than the current moving distance and the visible height of the scroll view. Find the last if (cumulativeNum> = (scroll. verticalOffset + scroll. viewportHeight) {// record the last index lastVisibleIndex = I; Down (); // The first and last items found have exceeded the loop break ;};}}}

 

The last two animation methods are as follows:

/// <Summary> // scroll Down, move the class content up /// </summary> private void Down () {if (firstVisibleIndex = oldFirstVisibleIndex & lastVisibleIndex = oldLastVisibleIndex) | oldFirstVisibleIndex = 0 & oldLastVisibleIndex = 0) return; // determine whether the current last item is greater than the last one moved if (lastVisibleIndex> oldLastVisibleIndex) {// obtain the Visual Object var _ item = ListView. containerFromIndex (lastVisibleIndex) as ListViewItem; // tt = new Transla TeTransform (); // determine whether the current visualization is empty. If you move faster, the list virtualization will not provide the object. If (_ item = null) {return;} _ item. renderTransform = tt; Storyboard board = new Storyboard (); // create a double animation DoubleAnimation animation = new DoubleAnimation () {AutoReverse = false, RepeatBehavior = new RepeatBehavior (1 ), enableDependentAnimation = true, To = 0, From = _ item. actualWidth/2, Duration = TimeSpan. fromSeconds (0.2)}; Storyboard. setTarget (animation, tt); Storyboard. setTargetProperty (animation, nameof (TranslateTransform. x); board. children. add (animation); board. begin () ;}/// <summary> // the scroll bar is Up and the content is down /// </summary> private void Up () {if (firstVisibleIndex <oldFirstVisibleIndex) {var _ item = ListView. containerFromIndex (firstVisibleIndex) as ListViewItem; tt = new TranslateTransform (); if (_ item = null) {return;} _ item. renderTransform = tt; Storyboard board = new Storyboard (); DoubleAnimation animation = new DoubleAnimation () {AutoReverse = false, RepeatBehavior = new RepeatBehavior (1), true, To = 0, from = _ item. actualWidth/2, Duration = TimeSpan. fromSeconds (0.3)}; Storyboard. setTarget (animation, tt); Storyboard. setTargetProperty (animation, nameof (TranslateTransform. x); board. children. add (animation); board. begin ();}}

 

This class has been completed. Finally, let's debug it at the front end: front-end code:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">        <ListView x:Name="listView"   >            <ListView.ItemContainerStyle>                <Style TargetType="ListViewItem" >                    <Setter Property="HorizontalContentAlignment" Value="Stretch" ></Setter>                </Style>            </ListView.ItemContainerStyle>            <ListView.ItemTemplate>                <DataTemplate>                    <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  >                        <Rectangle Height="100" Fill="Red"  HorizontalAlignment="Stretch"  Margin="5" ></Rectangle>                        <TextBlock Text="{Binding }" FontSize="50" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="20" ></TextBlock>                    </Grid>                </DataTemplate>            </ListView.ItemTemplate>                                                                    <interactivity:Interaction.Behaviors>                <local:ListViewBehavior></local:ListViewBehavior>            </interactivity:Interaction.Behaviors>        </ListView>            </Grid>

In this way, we have completed a special scrolling list effect. You can modify the animation effect in the Down and Up methods to make it more cool,
The first time I wrote a blog ....... Who

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.