Xamarin XAML ListView - How to select programmatically - c#

I am developing a windows mobile application with Xamarin, but don't seem to be able to programmatically set the selected ListView item.
I have tried the following ListViews methods and still nothing
SelectedItem
ScrollTo()
Focus()
I have also googled it and can't seem anything to say how to do this.
How do I do this?

This works fine in my sample app:
public partial class ItemsPage : ContentPage
{
public ItemsPage()
{
InitializeComponent();
Vm = new ItemsViewModel();
BindingContext = Vm;
}
protected override void OnAppearing()
{
ListviewItems.SelectedItem = Vm.Items[1];
}
public ItemsViewModel Vm { get; private set; }
In my sample app, ItemsViewModel.Items is a List<string>.
The second item in the list is set selected after this line of code runs in OnAppearing.

setting the SelectedItem property is the "correct" way to do it. What specifically is not happening that you think you happen when it is set?

I used a method but it may not be the most effective one. You can set your change to the list which was created by your model type and then you should reload the list view.
subjects[i].something=false;//set something
yourListView.ItemSource=null;
yourListView.ItemSource=subjects;

if you want to scroll to the specific location,
I am using
listChat.SetSelection(currentIndex);
in one of my chat application and it works fine.
if you are looking for the solution to scroll to desired position, even I have searched for the solution on internet, nothing helped. finally this one was my work around to make it work.

Related

ReactiveUI Example with Avalonia : UserControl View not working

I tried to implement Reactive UI Example using Avalonia with ReactiveUI. The search works, I can print on the console the elements resulting from it and there is a "slot" for each of them in the UI (the lines appear but are empty), but the NuggetDetailView does not show as the list's items.
I have activated View for ViewModel scan in the Initialize method of my Avalonia app :
public class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
Locator.CurrentMutable.RegisterViewsForViewModels(Assembly.GetCallingAssembly());
}
....
}
I do not get any error so I'm a bit lost on what I did wrong.
Thank you in advance,
Turns out the reflection-based View scanning was not working.
I changed
Locator.CurrentMutable.RegisterViewsForViewModels(Assembly.GetCallingAssembly());
to
Locator.CurrentMutable.Register(() => new NugetDetailsView(), typeof(IViewFor<NugetDetailsViewModel>));
And it worked

How to best implement a log in page with Caliburn.Micro MVVM

I am new to using caliburn.micro and currently learning MVVM.
I am using the windows template studio to create my UWP app, and it works great! But unfortunately, I am not familiar with MVVM and still learning UWP.
I get how the navigation works etc and how the shellpage is loaded. However, I want to prompt the user to log in upon opening the app (i.e. a login in page will start with no navigation sidebar).
I also want to make sure I'm following best practices...
I have tried substituting the MainViewModel with LoginViewModel which I get works, however, I don't want to create the navigation pane. I get that this is triggered by the "new Lazy(CreateShell)". I'm just not sure if I want to remove this from the activation service and call a method upon login?
Below is the default code supplied by the windows template studio which triggers on activation of the app if I understand correctly.
private ActivationService CreateActivationService()
{
return new ActivationService(_container, typeof(ViewModels.LoginViewModel), new Lazy<UIElement>(CreateShell));
}
private UIElement CreateShell()
{
var shellPage = new Views.ShellPage();
_container.RegisterInstance(typeof(IConnectedAnimationService), nameof(IConnectedAnimationService), new ConnectedAnimationService(shellPage.GetFrame()));
return shellPage;
}
I just need to be pointed in the right direction or lead to a video/tutorial as I'm struggling!!! any help much appreciated.
If you want to show login page,you can remove the ShellPage.It is a navigation view.
in App.xaml.cs
private ActivationService CreateActivationService()
{​
return new ActivationService(this, typeof(LoginPage));​
}​
​
private UIElement CreateShell()​
{​
return new Views.ShellPage();​
}
When login successfully,if you want to show the navigation view,you can set the ShellPage to the content of current window.
Window.Current.Content = new Views.ShellPage();

Modify HamburgerButtonVisibility property from different views

I'm using the fantastic Template10 for my Universal App and MVVM..
What I'm trying to do is to hide and show the hamburger button declared in the Shell.xaml file from a different view. The ideal solution would be something like.. If I don't say nothing, then show the hamburger button, otherwise, hide the hamburger button..
Let's suppose I have the MainPage and when I click an item in the list I navigate to the DetailsPage, in the constructor I send a message or set a property that infor the ShellView to hide the Hamburger button.
What's the best practice for doing that?
Messenger can be a possibilty imho but I'm not sure that is the best solution..
If you are using Template10 then in the Shell.xaml.cs you should have this:
public static Shell Instance { get; set; }
public static HamburgerMenu HamburgerMenu { get { return Instance.MyHamburgerMenu; } }
public Shell()
{
Instance = this;
this.InitializeComponent();
}
Which will allow you to access the shell instance from anywhere from you app, and with code:
var h = Shell.HamburgerMenu;
h.HamburgerButtonVisibility = MyVisibilityParam;
you can acces the visibility of the HamburgerButton, MyVisibilityparam here can be Visibility.Collapsed or Visibility.Visible
I think Messenger will fit well in here, fire it from other Views to update the button.

Correct way to transfer SelectedItemViewModel to another page in Windows Phone 8.1

I'm currently building a universal app but I'm concentrating on the WP8.1 part of it right now. I'm using MVVMLight with this project.
For simplicity sake, we'll just assume that I only have 2 pages in the project.
Page1.xaml contains a list which has various items. The Page1.xaml is binded to its own ViewModel i.e. Page1ViewModel. Each item in the list represents a viewModel i.e. ItemViewModel.
When I tap on an item, I call the following code:
public RelayCommand<ItemViewModel> ItemTapCommand
{
get
{
return this._itemTapCommand ?? (this._itemTapCommand =
new RelayCommand<ItemViewModel>((msg) =>
ExecuteItempTapCommand(msg)));
}
}
When an item in the list is tapped, I call the following code:
private object ExecuteItempTapCommand(ItemViewModel selectedItemViewModel)
{
Page2ViewModel page2ViewModel =
SimpleIoc.Default.GetInstance<ItemViewModel>();
page2ViewModel.SelectedItem = selectedItemViewModel;
_navigationService.Navigate(typeof(Page2),
selectedItemViewModel);
return null;
}
As you can see I'm using my Ioc to create get an instance of my Page2ViewModel and I then set the SelectedItem to the selectedItemViewModel.
Once it is set, I navigate to Page2 which is binded to my Page2ViewModel.
What I want to know is, is the above is ok to do? I've seen plenty of examples when dealing with passing object from one page to another is done by passing an Id for example and then I request the information from Page2, but why request it again when most of the information I need is already in my SelectedItemViewModel since it represents the tapped item in my list in Page1.
If it's not correct, what is the best way to go about this using MVVMLight?
Can you provide a sample? I've seen something about Messaging but I'm not sure how this would work as if I navigate to my page2, the Page2ViewModel will only be initiated when the page is created, so how can it receive a message? The way I have it above seems to initiate the Page2ViewModel and my Pag2 loads, it's re-using it and everything bind correctly but I'm not sure this is the correct way to go about it.
Any help would be appreciated.
Thanks.
In your Page2ViewModel, why not use
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Page2SelectedItem = e.Parameter as ItemViewModel;
base.OnNavigatedTo(e);
}
It looks like you are packing that data in with your _navigationService.Navigate call already.
With that set up, what happens if you just change to:
private object ExecuteItempTapCommand(ItemViewModel selectedItemViewModel)
{
_navigationService.Navigate(typeof(Page2), selectedItemViewModel);
return null;
}
You can use the ViewModel to get it if you do some work before that.
Read this blog post by Marco Minerva called Calling ViewModel methods in response to Page navigation events using MVVM Light in WinRT
which explains how to react to OnNavigatedTo and OnNavigatedFrom in the ViewModel.
It's a very cool solution.

Getting SelectedItem Issue on ComboBox - MVVM ObservableCollection

Firstly, my apologies to any one who may feel like this is a very dumb question or a question that has already been answered. I'm very new to MVVM, XAML and having read everything on StackOverflow, I'm still failing to understand what I'm sure is a simple concept.
So I have a MVVM set up where an Observable Collection is put into a ComboBox. Here is the view.
public class AppSettings : INotifyPropertyChanged
{
public class Regions
{
public int code { get; set; }
public string region { get; set; }
}
private ObservableCollection<Regions> _ItemsRegions = new ObservableCollection<Regions>
{
new Regions() { code = 0, region = "Metro : All Areas" },
new Regions() { code = 25, region = "Metro : North of River"},
new Regions() { code = 26, region = "Metro : South of River"},
new Regions() { code = 27, region = "Metro : East/Hills"},
};
public ObservableCollection<Regions> Region
{
get { return this._ItemsRegions; }
}
private Regions _selectedRegion;
public Regions SelectedRegion
{
get { return _selectedRegion; }
set
{
if (value != _selectedRegion)
{
_selectedRegion = value;
RaisePropertyChanged("SelectedRegion");
}
}
}
And for reference, here is my ComboBox.
<ComboBox Name="Regions" ItemsSource="{Binding Region}" DisplayMemberPath="region" SelectedItem="{Binding SelectedRegion, Mode=TwoWay}"/>
Now the good news is that I have the SelectedItem working and I'm able to with the MVVM obtain the values I need to make changes etc. which is great! That concept was a little difficult to grasp at first but once I had it, I knew what was going on. So I can save the data in any way at this point.... The eventual plan is to put it in roaming data. This is a Universal App.
So the problem is the user is finished with this page and navigates away from it . When he/she comes back to it the ComboBox is loaded with all the data (as expected) but the SelectedItem that I just saved is not. As in, the "IsSelected = True" item is null so it just says "choose an item".
What do I need to do in order to on page load, get the SelectedItem from save and set it to the ComboBox. I've been stupid and tried setting the Region.ComboBox.SelectedItem to a "string", but of course that defeats and destroys the whole MVVM purpose!
So, what do I need to do? I'm happy to be just pointed at some documentation for me to read.
Update Edit
So following advise from a user on here I took my get; set INotifyPropertyChanged logic and put it in a blank app. Just to see that I'm not doing anything stupid.
Unfortunately the blank app also has the same problem where navigation away from the page and back to it has none of my previously selected values... To illustrate this, here is a quick screenshot.
To navigate back, I'm using the hardware back button.
I'm guessing that I'm just missing a piece of the puzzle to make this work. This whole MVVM XAML concept is new to me and while I'm learning a lot about it, I'm genuinely stuck on this!
Any takers? Tips? Ideas? Examples?
Update 2
Okay so following some more advise posted in the comments on this question, I went and added a debugger track on the Object ID for "this._selectedRegion".
The watch of the Object ID shows that the data is in fact set correctly when a user selects one of the items from the combobox. Great! But when the user navigates away from the page and comes back to it, it's set to null. Not Great!
With my bland/stupid face am I missing the point completely? Am I meant to be on "OnNavigatedTo" aka, fist load setting the SelectedItem for the combobox myself? As in the data is never saved on navigation away and coming back to it is setting is null is in fact expected in MVVM? Do I manipulate the "get" statement and specify the ObservableCollection Item it's meant to be? Crude way, but like
_selectedRegion = something
return _selectedRegion
This sounds awfully crude to me and not what it should be, but maybe I'm just not appreciating the MVVM set up properly?
Thoughts anyone?
For a ComboBox in WPF it is very important to set SelectedItem to one of the items in ItemsSource.
Make sure that SelectedItem has the correct value (or is set) when he/she comes back.
Edit
Your binding
SelectedItem="{Binding SelectedRegion, Mode=TwoWay}"
will call the getter of SelectedRegion when the control is built. It will call the setter when the value in the ComboBox changes.

Categories