如何在Listview上使用ScrollTo方法

时间:2017-07-11 05:02:49

标签: listview xamarin mvvm xamarin.forms prism

我有使用棱镜的xamarin表单应用程序。我使用绑定到ListView的{​​{1}},但每当列表视图再次打开时,它都需要滚动到列表视图中之前选择的项目。

ScrollTo有一个方法,但是如何使用prism实现它呢?

你能帮我解决这个问题吗?

ObservableCollection<string>

1 个答案:

答案 0 :(得分:2)

您可以尝试以下内容:

首先在资源中使用EventAggregator,以便将其添加到XAML中的行为属性。

public class App : PrismApplication
{
    protected override async void OnInitialized()
    {
        Resources.Add("eventAggregator", Container.Resolve<IEventAggregator>());
        await NavigationService.NavigateAsync("MainPage");
    }
}

创建一个事件,该事件采用您在ObservableCollection

中的模型类型
public class ScrollToMyModelEvent : PubSubEvent<MyModel>
{
}

使用IEventAggregator的属性添加行为。 注意您不需要将该属性作为可绑定属性,或者实际上是可观察的。您真正需要的是确保在设置EventAggregator时订阅该事件。

public class ScrollToMyModelBehavior : BehaviorBase<ListView>
{
    private IEventAggregator _eventAggregator;
    public IEventAggregator EventAggregator
    {
        get => _eventAggregator;
        set
        {
            if(!EqualityComparer<IEventAggregator>.Default.Equals(_eventAggregator, value))
            {
                _eventAggregator = value;
                _eventAggregator.GetEvent<ScrollToMyModelEvent>().Subscribe(OnScrollToEventPublished);
            }
        }
    }

    private void OnScrollToEventPublished(MyModel model)
    {
        AssociatedObject.ScrollTo(model, ScrollToPosition.Start, true);
    }

    protected override void OnDetachingFrom(ListView bindable)
    {
        base.OnDetachingFrom(bindable);
        // The Event Aggregator uses weak references so forgetting to do this
        // shouldn't create a problem, but it is a better practice.
        EventAggregator.GetEvent<ScrollToMyModelEvent>().Unsubscribe(OnScrollToEventPublished);
    }
}

在ViewModel中,您现在只需要发布该事件。您可以在此处显示,只有在您导航回视图时才会执行此操作。然后在Behavior中处理它并将其传递给ListView的ScrollTo方法。

public class MyListPageViewModel : BindableBase, INavigatedAware
{
    private IEventAggregator _eventAggregator { get; }

    public MyListPageViewModel(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
    }

    public ObservableCollection<MyModel> MyModels { get; set; }

    public MyModel SelectedModel { get; set; }

    public void OnNavigatedTo(NavigationParameters)
    {
        if(parameters.GetNavigationMode() == NavigationMode.Back && 
           SelectedModel != null)
        {
            _eventAggregator.GetEvent<ScrollToMyModelEvent>()
                            .Publish(SelectedModel);
        }
    }
}

然后在你的视图中

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:behavior="clr-namespace:AwesomeApp.Behaviors" 
             x:Class="AwesomeApp.ScrollToPage">
    <ListView>
        <ListView.Behaviors>
            <behavior:ScrollToMyModelBehavior EventAggregator="{StaticResource eventAggregator}" />
        </ListView.Behaviors>
    </ListView>
</ContentPage>