星空网 > 软件开发 > ASP.net

“Win10 UAP 开发系列”之 在MVVM模式中控制ListView滚动位置

这个扩展属性从WP8.1就开始用了,主要是为了解决MVVM模式中无法直接控制ListView滚动位置的问题。比如在VM中刷新了数据,需要将View中的ListView滚动到顶部,ListView只有一个ScrollIntoView()方法可以控制滚动的位置,但最好在VM中不要出现直接控制View的代码,需要通过其他的方式。

使用一个扩展属性即可实现:

/// <summary>  /// 将ListView滚动到顶部 使用方法:在ListView增加扩展属性  /// ext:ListViewScrollToProperties.ScrollToIndex="{Binding ScrollToIndex}"  /// 在VM中先vm.ScrollToIndex = 1;再vm.ScrollToIndex = 0;  /// </summary>  public class ListViewScrollToProperties : DependencyObject  {    public static readonly DependencyProperty ScrollToIndexProperty =      DependencyProperty.RegisterAttached("ScrollToIndex", typeof(int), typeof(ListViewScrollToProperties), new PropertyMetadata("", OnScrollToIndexChanged));    public static string GetScrollToIndex(DependencyObject dependencyObject)    {      return (string)dependencyObject.GetValue(ScrollToIndexProperty);    }    public static void SetScrollToIndex(DependencyObject dependencyObject, string scrollToIndex)    {      dependencyObject.SetValue(ScrollToIndexProperty, scrollToIndex);    }    private static void OnScrollToIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)    {      if ((int)e.NewValue != 1)      {        var listview = (ListView)d;        if (listview != null)        {          if (listview.Items.Count > 0)          {            try            {              var target = listview.Items[int.Parse(e.NewValue.ToString())];              if (target != null)              {                listview.UpdateLayout();                listview.ScrollIntoView(target);              }            }            catch (Exception ex)            {              System.Diagnostics.Debug.WriteLine(ex.Message);            }          }        }      }    }  }

使用方式比较丑,可以将就用:

在VM中提供一个ScrollToIndex属性,绑定到ListView上:

<ListView ItemsSource="{Binding ArticleItemList}"                controlHelper:ListViewScrollToProperties.ScrollToIndex="{Binding ScrollToIndex}"               Margin="0"></ListView>

在VM中刷新数据后,需要手动更改值来触发:

//滚动到顶部ScrollToIndex = 1;ScrollToIndex = 0;

我觉得这种实现方式比较丑,如果大家有好的实现方式欢迎留言讨论。

 




原标题:“Win10 UAP 开发系列”之 在MVVM模式中控制ListView滚动位置

关键词:ie

ie
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

PSPP计划:https://www.ikjzd.com/w/1573203872944922626
天津港(集团)有限公司:https://www.ikjzd.com/w/1573203873980915714
点达供应链:https://www.ikjzd.com/w/1573203879761010690
赶鸭子跨境购:https://www.ikjzd.com/w/1573203883426832386
普惠制:https://www.ikjzd.com/w/1573203892188733441
铺货模式:https://www.ikjzd.com/w/1573203892910153729
深圳到西安自驾路线攻略 深圳到西安自驾最佳路线:https://www.vstour.cn/a/411228.html
松花蛋是哪里的特产松花蛋的产地:https://www.vstour.cn/a/411229.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流