【问题标题】:Xamarin forms scroll to buttomXamarin 表单滚动到底部
【发布时间】:2017-03-18 19:13:10
【问题描述】:

我正在创建一个 Xamarin foms 应用程序,随着时间的推移,我将收到消息,并且我总是希望新消息显示在我的 ListView 的按钮上。

目前我的页面是这样的:

 <StackLayout>
   <Button  Text="Login"  />
   <ListView  x:Name="MessageBox" ItemsSource="{Binding TempTest}" ></ListView>
   <Button Command="{Binding AddMessage}" Text="Login"/>
 </StackLayout>

我不知道如何从我的 ViewModel 类中滚动,关于如何实现这一点的任何想法?

到目前为止我能找到的最好的是:http://www.infinite-x.net/2014/10/30/using-the-xamarin-forms-1-3-0-listview-scrollto-method/

但在这个阶段他甚至没有考虑使用 MVVM。

【问题讨论】:

  • 您是否要滚动到Buttons 之一?您在代码中拥有的两个 Buttons 都在 ListView 之外,因此它们将无法滚动到。
  • 我的按钮有一个绑定到另一个类的命令,从那个类我将新消息添加到我的视图中。添加消息后,我想滚动视图以显示完整的消息(不管我添加到滚动视图中的消息数量)
  • 您的意思是滚动到按钮还是底部

标签: mvvm xamarin.forms


【解决方案1】:

嗯,一种不太优雅的方法,我知道解决这个问题的方法是从您的 ViewModel 中公开一个 Action&lt;Message&gt;,然后您的 ContentPage 将初始化该 Action 并告诉它进行滚动。类似于以下内容(只需将 Message 替换为真实型号名称即可)。

内容页面:

public partial class MessagePage : ContentPage {

    private MessageViewModel _viewModel;

    public MessagePage() {
        _viewModel = new MessageViewModel();

        BindingContext = _viewModel;

        _viewModel.OnMessageAdded = message => { //We tell the action to scroll to the passed in object here
            MessageBox.ScrollTo(message, ScrollToPosition.MakeVisible, true);
        }
    }
}

视图模型:

public class MessageViewModel {
    public Action<Message> OnMessageAdded { get; set; }

    public ICommand AddMessage { get; protected set; }

    private ObservableCollection<Message> _tempTest;
    public  ObservableCollection<Message> TempTest {
        get { return _tempTest ?? (_tempTest = new ObservableCollection<Message>()); }
        set {
            if(_tempTest != value) {
                _tempTest = value;
                OnPropertyChanged();
            }
        }
    }

    public MessageViewModel() {
        AddMessage = new Command(async () => {
            Message message = SomeClass.GetMessage(); //Get your object from your separate class

            TempTest.Add(message); //Add it to the list that your ListView binds to

            OnMessageAdded?.Invoke(message); //Now run the Action which, if it is not null, your ContentPage should have set to do the scrolling

            //Or if you are not using C#6:
            //Action<Message> onMessageAdded = OnMessageAdded;

            //if(onMessageAdded != null) { onMessageAdded.Invoke(message); }
        });
    }
}

【讨论】:

  • 我最终使用了您推荐的东西,谢谢!
  • @BenjaminKarlog 很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 2014-12-12
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
  • 2016-11-13
  • 2016-11-22
相关资源
最近更新 更多