我创建了一个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。
答案 0 :(得分:2)
那么,不是优雅的方式,我知道解决这个问题就是从你的ViewModel中暴露Action<Message>
,然后你的ContentPage
会初始化Action
并告诉它滚动。类似于以下内容(只需将Message
替换为真正的模型名称)。
ContentPage:
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); }
});
}
}