Pass data back from Maui shell navigation - maui

The App navigates to a view in which the user selects an item on a CollectionView and then navigates back. How do I get the SelectedItem on the page that initiated the navigation?
await Shell.Current.GoToAsync("//SelectAnItem");
//Get the selected item

The App navigates to a view in which the user selects an item on a
CollectionView and then navigates back.
There are several ways to achieve this.
Method 1:A common approach is to use EventHandler.
You can define EventHandler in this view(Suppose the name is SelectedPage), just as follows:
public static EventHandler<Item> mEventHandler; // define a static EventHandler
After you select an item, you can pass the selected item with the following code:
private void Button_Clicked(object sender, EventArgs e)
{
EventHandler<Item> handler = mEventHandler;
if (handler != null)
{
Item item = new Item { Name= "Hello." };
mEventHandler(this, item);
}
Navigation.PopAsync();
}
In the previous page, you can add the following code in the constructor of YourPreviousPage :
SelectedPage.mEventHandler += delegate (object s, Item a)
{
BackCall(s, a);
};
And the code of function BackCall is:
private void BackCall(object send, Item a)
{
if (a == null)
{
throw new ArgumentNullException(nameof(a));
}
else {
DisplayAlert("Alert", "call back value is : " + a.Name, "OK");
}
}
method 2
You can also use MessagingCenter to achieve this function.
Please refer to the following code:
public partial class PreviousPage: ContentPage
{
public PreviousPage()
{
InitializeComponent();
// method 2
MessagingCenter.Subscribe<SelectedPage, Item>(this, "SelectedItem", (obj, item) =>
{
var newItem = item as Item;
DisplayAlert("Alert", "call back value is : " + newItem.Name, "OK");
});
}
}
SelectedPage.xaml.cs
private void Button_Clicked(object sender, EventArgs e)
{
Item item = new Item { Name = "Hello." };
MessagingCenter.Send(this, "SelectedItem", item);
Navigation.PopAsync();
}

Related

Make focus go to next entry in a collection view

I have an application in .Net Maui that uses a collection view with an entry field and after the collection view one static entry field. If you are currently focused on the first entry in the collection view and hit tab or enter it will not navigate to the next entry in the collection view and focus on the static entry field. I need to find the best way to have the entry focus on the next entry in the collection view on complete.
I have tried changing the return type of the collection view entry field to Next and also tried the community toolkit SetFocusOnEntryCompletedBehavior function and both result in the same behavior of not navigating to the next entry from the collection view. Very similar to this issue that doesnt seem to be resolved. MAUI - CollectionView jump / focus to next entry
I found a workaround for you. You could try the following code:
Step1 Create a custom control , let's call it MyEntry (MyEntry.cs) which subclass Entry:
In this control we attach a BindableProperty IsExpectedToFocusProperty which we used it to judge whether it is goning to be focused. We also registered a new method OnIsExpectedToFocus to detect propertyChanged for our control. For info about BindableProperty, you could refer to Bindable properties.
MyEntry.cs,
public class MyEntry : Entry
{
public static readonly BindableProperty IsExpectedToFocusProperty = BindableProperty.Create("IsExpectedToFocus", typeof(bool), typeof(MyEntry), false, propertyChanged:OnIsExpectedToFocus);
public bool IsExpectedToFocus
{
get => (bool)GetValue(IsExpectedToFocusProperty);
set => SetValue(IsExpectedToFocusProperty, value);
}
static void OnIsExpectedToFocus(BindableObject bindable, object oldValue, object newValue)
{
// Property changed implementation goes here
if ((bool)newValue == true)
{
(bindable as Entry).Focus();
}
}
}
Step2 Consume custom control in CollectionView. We define the ReturnCommand and its parameter. we will bind them in the MainPageViewModel.
MainPage.xaml,
<CollectionView x:Name="mycoll" ItemsSource="{Binding ItemCollection}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<local:MyEntry x:Name="myentry" Focused="myentry_Focused"
IsExpectedToFocus="{Binding IsExpectedToFocus}"
Text="{Binding Title,Mode=TwoWay}" TextColor="Black"
ReturnCommand="{Binding Source={RelativeSource AncestorType={x:Type local:MainPageViewModel}}, Path=ReturnCommand}"
ReturnCommandParameter="{Binding .}"/>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
In .cs file:
void myentry_Focused(System.Object sender, Microsoft.Maui.Controls.FocusEventArgs e)
{
var entry = sender as Entry;
foreach (var item in viewModel.ItemCollection)
{
if (entry.BindingContext != item)
{
item.IsExpectedToFocus = false;
}
}
}
Step3 Design our MainPageViewModel. I define an ObservableCollection which ItemSource will bind to. And add three items just for test.
Then I think the most important part is to design the Command. Let me explain it briefly. When we press the entry of an Entry, we fire the ReturnCommand and get current Item through ReturnCommandParameter. We get the index of current Item in ItemCollection. So the next entry which needs to be focused corresponds to the index+1 Item. Then we changed the IsExpectedToFocus of the next entry and fire the OnIsExpectedToFocus method which set the entry be focused. Done!
MainPageViewModel.cs
public class MainPageViewModel
{
public ObservableCollection<Item> ItemCollection { get; set; } = new ObservableCollection<Item>();
public Command ReturnCommand
{
get
{
return new Command<Item>((e) =>
{
e.IsExpectedToFocus = false;
int index = ItemCollection.IndexOf(e); // get the current index
if (index != -1)
{
int nextIndex;
// if last entry, next index is 0, else index +1
if (index < (ItemCollection.Count() - 1))
{
nextIndex = index + 1;
ItemCollection[nextIndex].IsExpectedToFocus = true;
}
else if(index == (ItemCollection.Count() - 1))
{
nextIndex = 0;
ItemCollection[nextIndex].IsExpectedToFocus = true;
}
}
});
}
}
public MainPageViewModel()
{
//add three item for test
ItemCollection.Add(
new Item
{
Title = "12345",
IsExpectedToFocus = false
}) ;
ItemCollection.Add(
new Item
{
Title = "23456",
IsExpectedToFocus = false
});
ItemCollection.Add(
new Item
{
Title = "34567",
IsExpectedToFocus = false
});
}
}
Also, this is Item.cs, should implement INotifyPropertyChanged
public class Item : INotifyPropertyChanged
{
public string title;
public bool isExpectedToFocus;
public string Title
{
get
{
return title;
}
set
{
title = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Title)));
}
}
public bool IsExpectedToFocus
{
get
{
return isExpectedToFocus;
}
set
{
isExpectedToFocus = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsExpectedToFocus)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Hope it works for you.

Create WinUI3/MVVM Most Recently Used (MRU) List in Menu Bar

I would like to create a classic "Recent Files" list in my Windows app menu bar (similar to Visual Studio's menu bar -> File -> Recent Files -> see recent files list)
The MRU list (List < string > myMRUList...) is known and is not in focus of this question. The problem is how to display and bind/interact with the list according to the MVVM rules.
Microsoft.Toolkit.Uwp.UI.Controls's Menu class will be removed in a future release and they recommend to use MenuBar control from the WinUI. I haven't found any examples, that use WinUI's MenuBar to create a "Recent Files" list.
I'm using Template Studio to create a WinUI 3 app. In the ShellPage.xaml I added
<MenuFlyoutSubItem x:Name="mruFlyout" Text="Recent Files"></MenuFlyoutSubItem>
and in ShellPage.xaml.c
private void Button_Click(object sender, RoutedEventArgs e)
{
mruFlyout.Items.Insert(mruFlyout.Items.Count, new MenuFlyoutItem(){ Text = "C:\\Test1_" + DateTime.Now.ToString("MMMM dd") } );
mruFlyout.Items.Insert(mruFlyout.Items.Count, new MenuFlyoutItem(){ Text = "C:\\Test2_" + DateTime.Now.ToString("MMMM dd") } );
mruFlyout.Items.Insert(mruFlyout.Items.Count, new MenuFlyoutItem(){ Text = "C:\\Test3_" + DateTime.Now.ToString("MMMM dd") } );
}
knowing this is not MVVM, but even this approach does not work properly, because the dynamically generated MenuFlyoutItem can be updated only once by Button_Click() event.
Could anybody give me an example, how to create the "Recent Files" functionality, but any help would be great! Thanks
Unfortunately, it seems that there is no better solution than handling this in code behind since the Items collection is readonly and also doesn't response to changes in the UI Layout.
In addition to that, note that because of https://github.com/microsoft/microsoft-ui-xaml/issues/7797, updating the Items collection does not get reflected until the Flyout has been closed and reopened.
So assuming your ViewModel has an ObservableCollection, I would probably do this:
// 1. Register collection changed
MyViewModel.RecentFiles.CollectionChanged += RecentFilesChanged;
// 2. Handle collection change
private void RecentFilesChanged(object sender, NotifyCollectionChangedEventArgs args)
{
// 3. Create new UI collection
var flyoutItems = list.Select(entry =>
new MenuFlyoutItem()
{
Text = entry.Name
}
);
// 4. Updating your MenuFlyoutItem
mruFlyout.Items.Clear();
flyoutItems.ForEach(entry => mruFlyout.Items.Add(entry));
}
Based on chingucoding's answer I got to the "recent files list" binding working.
For completeness I post the detailed code snippets here (keep in mind, that I'm not an expert):
Again using Template Studio to create a WinUI 3 app.
ShellViewModel.cs
// constructor
public ShellViewModel(INavigationService navigationService, ILocalSettingsService localSettingsService)
{
...
MRUUpdateItems();
}
ShellViewModel_RecentFiles.cs ( <-- partial class )
using System.Collections.ObjectModel;
using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.Storage.Pickers;
namespace App_MostRecentUsedTest.ViewModels;
public partial class ShellViewModel : ObservableRecipient
{
public ObservableCollection<MRUItem> MRUItems{ get; set;} = new();
// update ObservableCollection<MRUItem>MRUItems from MostRecentlyUsedList
public void MRUUpdateItems()
{
var mruTokenList = StorageApplicationPermissions.MostRecentlyUsedList.Entries.Select(entry => entry.Token).ToList();
var mruMetadataList = StorageApplicationPermissions.MostRecentlyUsedList.Entries.Select(entry => entry.Metadata).ToList(); // contains path as string
MRUItems.Clear(); var i = 0;
foreach (var path in mruMetadataList)
{
MRUItems.Add(new MRUItem() { Path = path, Token = mruTokenList[i++] });
}
}
// called if user selects a recent used file from menu bar list
[RelayCommand]
protected async Task MRULoadFileClicked(int? fileId)
{
if (fileId is not null)
{
var mruItem = MRUItems[(int)fileId];
FileInfo fInfo = new FileInfo(mruItem.Path ?? "");
if (fInfo.Exists)
{
StorageFile? file = await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruItem.Token);
if (file is not null)
{
Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, file.Path); // store file.Path into Metadata
MRUUpdateItems();
// LOAD_FILE(file);
}
}
else
{
}
}
await Task.CompletedTask;
}
[RelayCommand]
protected async Task MenuLoadFileClicked()
{
StorageFile? file = await GetFilePathAsync();
if (file is not null)
{
Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, file.Path); // store file.Path into Metadata
MRUUpdateItems();
// LOAD_FILE(file);
}
await Task.CompletedTask;
}
// get file path with filePicker
private async Task<StorageFile?> GetFilePathAsync()
{
FileOpenPicker filePicker = new();
filePicker.FileTypeFilter.Add(".txt");
IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
WinRT.Interop.InitializeWithWindow.Initialize(filePicker, hwnd);
return await filePicker.PickSingleFileAsync();
}
public class MRUItem : INotifyPropertyChanged
{
private string? path;
private string? token;
public string? Path
{
get => path;
set
{
path = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(path));
}
}
public string? Token
{
get => token;
set => token = value;
}
public event PropertyChangedEventHandler? PropertyChanged;
}
}
ShellPage.xaml
<MenuBar>
<MenuBarItem x:Name="ShellMenuBarItem_File">
<MenuFlyoutItem x:Uid="ShellMenuItem_File_Load" Command="{x:Bind ViewModel.MenuLoadFileClickedCommand}" />
<MenuFlyoutSubItem x:Name="MRUFlyout" Text="Recent Files..." />
</MenuBarItem>
</MenuBar>
ShellPage.xaml.cs
// constructor
public ShellPage(ShellViewModel viewModel)
{
...
// MRU initialziation
// assign RecentFilesChanged() to CollectionChanged-event
ViewModel.MRUItems.CollectionChanged += RecentFilesChanged;
// Add (and RemoveAt) trigger RecentFilesChanged-event to update MenuFlyoutItems
ViewModel.MRUItems.Add(new MRUItem() { Path = "", Token = ""});
ViewModel.MRUItems.RemoveAt(ViewModel.MRUItems.Count - 1);
}
// MRU Handle collection change
private void RecentFilesChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// project each MRUItems list element into a new UI MenuFlyoutItem flyoutItems list
var i = 0;
var flyoutItems = ViewModel.MRUItems.Select(entry =>
new MenuFlyoutItem()
{
Text = " " + i.ToString() + " " + FilenameHelper.EllipsisString(entry.Path, 65),
Command = ViewModel.MRULoadFileClickedCommand,
CommandParameter = i++
}
);
//// If you want to update the list while it is shown,
//// you will need to create a new FlyoutItem because of
//// https://github.com/microsoft/microsoft-ui-xaml/issues/7797
// Create a new flyout and populate it
var newFlyout = new MenuFlyoutSubItem();
newFlyout.Text = MRUFlyout.Text; // Text="Recent Files...";
// Updating your MenuFlyoutItem
flyoutItems.ToList().ForEach(item => newFlyout.Items.Add(item));
// Get index of old sub item and remove it
var oldIndex = ShellMenuBarItem_File.Items.IndexOf(MRUFlyout);
ShellMenuBarItem_File.Items.Remove(MRUFlyout);
// Insert the new flyout at the correct position
ShellMenuBarItem_File.Items.Insert(oldIndex, newFlyout);
// Assign newFlyout to "old"-MRUFlyout
MRUFlyout = newFlyout;
}

Xamarin Forms and TabGestureRecognizer does not fire with Command

I have this problem with Xamarin Forms (Tested on Android and iOS).
I have a simple page
using System;
using Xamarin.Forms;
namespace BugTGR
{
public class PageMain : ContentPage
{
public PageMain()
{
PageMainViewModel vm = new PageMainViewModel();
this.BindingContext = vm;
Label label1 = new Label{ Text = "Press with ICommand"};
TapGestureRecognizer tgr = new TapGestureRecognizer();
tgr.BindingContext = vm;
tgr.SetBinding(TapGestureRecognizer.CommandProperty, "Tapped");
label1.GestureRecognizers.Add(tgr);
Label label2 = new Label { Text = "Press with Tapped"};
TapGestureRecognizer tgr1 = new TapGestureRecognizer();
tgr1.Tapped += async (object sender, EventArgs e) => {
await DisplayAlert("Attention", "PRESSED WITH TAPPED", "Ok");
};
label2.GestureRecognizers.Add(tgr1);
Content = new StackLayout
{
Children = {label1, label2}
};
}
}
}
In this code, I use this ViewModel (very simple, only a command)
using System;
using System.Windows.Input;
using Xamarin.Forms;
using PropertyChanged;
namespace BugTGR
{
[ImplementPropertyChanged]
public class PageMainViewModel
{
public PageMainViewModel()
{
this.Tapped = new Command(async() =>
{
await Application.Current.MainPage.DisplayAlert("Attention", "Pressed", "Ok");
});
}
public ICommand Tapped { protected get; set;}
}
}
Then, how you can see, I try to Bind the Command to a TapGestureRecognizer, then add the TGR to a label, but if I click the label, the command is not called.
In the second label (label2) I add another TapGestureRecognizer without bind the command, using Tapped event. This works!
There is someone that can let me know what am I doing wrong?
Thanks!
Alessandro
Here is working solution. The problem is how you create Tapped command.
Below is 2 ways of doing this. Command or event handler calling VM. If you are doing this in code and not in xaml I would use vm.TappedHandler method
namespace ButtonRendererDemo
{
public class LabelTapPage : ContentPage
{
public LabelTapPage()
{
PageMainViewModel vm = new PageMainViewModel();
this.BindingContext = vm;
Label label1 = new Label { Text = "Press with ICommand" };
TapGestureRecognizer tgr = new TapGestureRecognizer();
label1.GestureRecognizers.Add(tgr);
tgr.SetBinding(TapGestureRecognizer.CommandProperty, "Tapped");
Label label2 = new Label { Text = "Press with Tapped Event" };
TapGestureRecognizer tgr1 = new TapGestureRecognizer();
tgr1.Tapped += async (object sender, EventArgs e) => {
await DisplayAlert("Attention", "Tapped Event: Pressed", "Ok");
};
label2.GestureRecognizers.Add(tgr1);
Label label3 = new Label { Text = "Press with TappedHandler" };
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += async (s, e) => {
await vm.TappedHandler();
};
label3.GestureRecognizers.Add(tapGestureRecognizer);
Content = new StackLayout
{
Children = { label1, label2, label3 }
};
}
}
public class PageMainViewModel : INotifyPropertyChanged
{
ICommand tapCommand;
public PageMainViewModel()
{
tapCommand = new Command(OnTapped);
}
public async Task TappedHandler()
{
await Application.Current.MainPage.DisplayAlert("Attention", "TappedHandler: Pressed", "Ok");
}
public ICommand Tapped
{
get { return tapCommand; }
}
async void OnTapped(object s)
{
await Application.Current.MainPage.DisplayAlert("Attention", "Tapped Command: Pressed", "Ok");
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Also you don't need to set tgr.BindingContext = vm; It is inherited by your page
After I published it I found that there is much easier solution:
Remove "protected" in
public ICommand Tapped { get; set; }
so page can access it. That's it :-)
May be you meant make "set" protected not get?

How can I pass a listview from one form to another form?

I have 2 forms. form1 and form2. There is a button at form1 for me to access to form2 and in form2, I have a listview2 and some textboxes. I manage to input items into listview2. Then when I click on the OK button in form2, listview1 in form1 should show exactly like listview2. So guys, can anyone suggest me a way to do this? Thanks
Below are my codes. I hope I don't confuse you all.
Form1 code =>
namespace MainServerPage
{
public partial class MainServerPage : Form
{
public ListView LV;
public MainServerPage()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
AddItem Add = new AddItem(this); //to open form2
Add.ShowDialog();
}
}
}
Form2 code =>
namespace MainServerPage
{
public partial class AddItem : Form
{
MainServerPage currentform; //I learn this way of passing form to another but it's not working
public AddItem(MainServerPage incomingform)
{
currentform = incomingform;
InitializeComponent();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
ListViewItem item = new ListViewItem(txtCode.Text);
item.SubItems.Add(txtLocation.Text);
item.SubItems.Add(cbxStatus.Text);
item.SubItems.Add(txtWeatherHigh.ToString());
item.SubItems.Add(txtWeatherLow.ToString());
listView2.Items.Add(item); //send to listView2
txtCode.Text = "";
txtLocation.Text = "";
cbxStatus.Text = "";
txtWeatherHigh.Text = "";
txtWeatherLow.Text = "";
cbxZone.Text = "";
}
private void btnOk_Click(object sender, EventArgs e)
{
currentform.LV = load; //I got stuck here...do not know what to do
}
}
}
In general, it's not the list view you want to pass, it's the data that the list view is representing. You should probably rethink your design such that you btnUpdate_Click function builds a data object rather than building a ListViewItem directly. Then you can either pass the data object(s) back to your first form.

Trying to Add More tabs to tab panel upon clicking on a button

I would like to add more tabs to the tab panel upon receiving a reponse from a servelet.. the problem is that It only adds the last one and not the the others see part of the code below. It seems like it is only adding the last panel "Time Reports" but not the other two
Thank you
btnLogin.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
if(getLoginResult())
{
HorizontalPanel temp = new HorizontalPanel();
panel.add(temp, "Add Hours");
panel.add(temp, "Time Sheets");
panel.add(temp, "Time Reports");
}
}
});
RootPanel.get().add(panel);
}
private boolean getLoginResult() {
AsyncCallback callback = new AsyncCallback() {
public void onSuccess(Object result) {
isAuthenticated = true;
}
public void onFailure(Throwable caught) {
Window.alert("Error when invoking the pageable data service :" + caught.getMessage());
isAuthenticated = false;
}
};
timesheetLoginServlet.isAuthenticated("1","rapidjava", callback);
return isAuthenticated;
}
}
You can add any widget to its parent only once. Change the temp to temp1, temp2 and temp3