Navigation does not exist in current context Xamarin Comunity Toolkit Extensions - xamarin

I want to open a pop up window using xamarin comunity toolkit extensions but when i try to call
Navigation it says that it does not exist even if i have included xct.extensions. There is NavigationExtensions but I don't know what I'm supposed to pass as first parameter and it says that my FilterPopup is of incorect type
using Xamarin.CommunityToolkit.Extensions;
namespace Appointments.ViewModels
{
public class WallViewModel
{
public ObservableCollection<Stylist> Stylists { get; set; }
public AsyncCommand OpenModalFiltersComand;
public WallViewModel()
{
OpenModalFiltersComand = new AsyncCommand(OpenModalFilters);
}
async Task OpenModalFilters()
{
NavigationExtensions.ShowPopup(AppShell, FilterPopup);
Navigation // error
}
}
}
My FilterPopup
namespace Appointments.Popups
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class FilterPopup : Popup
{
public FilterPopup()
{
InitializeComponent();
}
}
}
EDIT---------
I'm using shell navigation

ShowPopup takes an INavigation and an instance of a PopupBase. Navigation is a property of Page types, so your VM does not have a reference to it.
var nav = App.Current.MainPage.Navigation;
var filter = new FilterPopup();
NavigationExtensions.ShowPopup(nav, filter);

Related

When I create a template object to be used inside my Xamarin Forms code, is there a way I can use C# fluent with Build to create the template?

I have a template class that is in its own namespace and that I add to my code with `
new InfoLabel()`{ Text = "abc" };
Note that this is just a very simple example and I have other template objects that don't just depend on one thing, for example an object with 2-3 labels.
Is there a way that I can apply Xamarin C# fluent to create a templated object?
Here is the simple example object that I have:
namespace Test
{
public class InfoLabel : Label
{
public InfoLabel()
{
SetDynamicResource(FontFamilyProperty, Const.Fonts.DefaultRegular);
SetDynamicResource(FontSizeProperty, Const.Fonts.InfoTextFontSize);
SetDynamicResource(TextColorProperty, Const.Colors.InfoLabelColor);
LineBreakMode = LineBreakMode.WordWrap;
VerticalOptions = LayoutOptions.Start;
HorizontalTextAlignment = TextAlignment.Start;
}
}
}
What I would like to know is how I can set up the same thing using the latest C# fluent standards?
Here is the way I think it might be done. I used a Build() method but I would appreciate if someone more skilled than me could tell me if I am doing it correctly as this is a big change from what I am used to:
namespace Test
{
public class InfoLabel
{
public InfoLabel()
{
Build();
}
void Build() =>
new Label
{
LineBreakMode = LineBreakMode.WordWrap,
}
.TextLeft()
.DynamicResources((Label.FontFamilyProperty, Const.Fonts.DefaultRegular),
(Label.FontSizeProperty, Const.Fonts.InfoTextFontSize),
(Label.TextColorProperty, Const.Colors.InfoLabelColor));
Here is another idea that I have:
namespace Test
{
public class InfoLabel : Label
{
public InfoLabel()
{
LineBreakMode = LineBreakMode.WordWrap;
Build();
}
void Build() =>
this.TextLeft()
.DynamicResources((Label.FontFamilyProperty, Const.Fonts.DefaultRegular),
(Label.FontSizeProperty, Const.Fonts.InfoTextFontSize),
(Label.TextColorProperty, Const.Colors.InfoLabelColor));
Note that I am using an extension method for the resources.
You could create the instance of label like following
public class InfoLabel : Label
{
static InfoLabel CreateDefaultLabel()
{
return new InfoLabel
{
LineBreakMode = LineBreakMode.WordWrap,
}
.TextLeft()
.DynamicResources((Label.FontFamilyProperty, Const.Fonts.DefaultRegular),
(Label.FontSizeProperty, Const.Fonts.InfoTextFontSize),
(Label.TextColorProperty, Const.Colors.InfoLabelColor));
}
}
var label = InfoLabel.CreateDefaultLabel();
For more details of the usage of markup you could check this blog .

Xamarin Shell navigation passing data to viewmodel doesn't work

I have a route that is registered using the following
Routing.RegisterRoute("SchoolHome", typeof(SchoolHomePage));
I have a page with a list of schools and when I tap a School it executes this just fine from the ViewModel Command
Shell.Current.GoToAsync($"SchoolHome?schoolid={selectedSchool.Id}");
Here is my SchoolHomePage.xaml.cs
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SchoolHomePage : ContentPage
{
public SchoolHomePage()
{
InitializeComponent();
BindingContext = new SchoolHomeViewModel();
}
}
Here is a snippet of SchoolHomeViewModel.cs
[QueryProperty("School", "schoolid")]
public class SchoolHomeViewModel : BaseViewModel
{
string school;
public string School
{
get
{
return school;
}
set
{
SetProperty(ref school, Uri.UnescapeDataString(value));
}
}
So Shell doesn't map my QueryProperty to my property School and the page doesn't navigate. If I put the QueryProperty in the ContentPage's code behind and set the ViewModel's School property there, it will pass the value along but the page still doesn't navigate. It just stays on the page with the list of schools with the one I just tapped being selected.
I found the problem. I had an issue with a property in my viewmodel. Once I fixed that it worked.

Dynamic ViewModel navigation

I am trying to find a way to be able to set from the View to what ViewModel I have to navigate. This is to be able to change the navigation flow without changing the core project.
I thought the easier way would be creating an interface, setting the target ViewModel there and injecting the interface into the ViewModel to then perform the navigation.
public interface IModelMapping
{
MvxViewModel ViewModelToNavigate();
}
public class MyViewModel : MvxViewModel
{
readonly IMvxNavigationService navigationService;
readonly IModelMapping modelMapping;
public MyViewModel(IMvxNavigationService navigationService, IModelMapping modelMapping)
{
this.navigationService = navigationService;
this.modelMapping = modelMapping;
}
public IMvxAsyncCommand GoContent
{
get
{
IMvxViewModel vm = modelMapping.ViewModelToNavigate();
IMvxAsyncCommand navigateCommand = new MvxAsyncCommand(() => navigationService.Navigate<vm>());
return navigteCommand;
}
}
}
The problem with this code is I am getting an error setting the navigationService.Navigate(). The error is 'vm is a variable but it is used like a type'
What about using the URI navigation together with the facade? See also https://www.mvvmcross.com/documentation/fundamentals/navigation#uri-navigation
Say you are building a task app and depending on the type of task you want to show a different view. This is where NavigationFacades come in handy (there is only so much regular expressions can do for you).
mvx://task/?id=00 <– this task is done, show read-only view (ViewModelA)
mvx://task/?id=01 <– this task isn’t, go straight to edit view (ViewModelB)
[assembly: MvxRouting(typeof(SimpleNavigationFacade), #"mvx://task/\?id=(?<id>[A-Z0-9]{32})$")]
namespace *.NavigationFacades
{
public class SimpleNavigationFacade
: IMvxNavigationFacade
{
public Task<MvxViewModelRequest> BuildViewModelRequest(string url,
IDictionary<string, string> currentParameters, MvxRequestedBy requestedBy)
{
// you can load data from a database etc.
// try not to do a lot of work here, as the user is waiting for the UI to do something ;)
var viewModelType = currentParameters["id"] == Guid.Empty.ToString("N") ? typeof(ViewModelA) : typeof(ViewModelB);
return Task.FromResult(new MvxViewModelRequest(viewModelType, new MvxBundle(), null, requestedBy));
}
}
}

How to play default button's sound on Xamarin.Android?

I'm making an app with using Xamarin.forms.
You might know forms' button is not enough to use as image button if you tried one.
So I use Image as a button and add gesturerecogniger. It's working fine.
Good thing is that I can use all Image's bindable property same like using Image. (like 'Aspect property' and else)
Only problem is that Android button has sound effect when it's pressed.
Mine doesn't have.
How to play default button sound on Android?
[another try]
I tried to make layout and put Image and empty dummy button on it.
But If I do this, I can't use any property of Image or Button unless I manually link it.
So I think it's not the right way.
Thanks.
Xamarin.Android:
var root = FindViewById<View>(Android.Resource.Id.Content);
root.PlaySoundEffect(SoundEffects.Click);
Android playSoundEffect(int soundConstant)
Xamarin.iOS
UIDevice.CurrentDevice.PlayInputClick();
Xamarin.Forms via Dependency Service:
public interface ISound
{
void KeyboardClick () ;
}
And then implement the platform specific function.
iOS:
public void KeyboardClick()
{
UIDevice.CurrentDevice.PlayInputClick();
}
Android:
public View root;
public void KeyboardClick()
{
if (root == null)
{
root = FindViewById<View>(Android.Resource.Id.Content);
}
root.PlaySoundEffect(SoundEffects.Click);
}
Xamarin Forms:
PCL interface:
interface ISoundService { void Click(); }
Click handler:
void Handle_OnClick(object sender, EventArgs e) {
DependencyService.Get<ISoundService>().Click();
}
Android:
public class MainActivity {
static MainActivity Instance { get; private set; }
OnCreate() {
Instance = this;
}
}
class SoundService : ISoundService {
public void Click() {
var activity = MainActivity.Instance;
var view = activity.FindViewById<View>(
Android.Resource.Id.Content);
view.PlaySoundEffect(SoundEffects.Click);
}
}
Take a look at the following:
MonoTouch.UIKit.IUIInputViewAudioFeedback
Interface that, together with the UIInputViewAudioFeedback_Extensions class, comprise the UIInputViewAudioFeedback protocol.
See Also: IUIInputViewAudioFeedback
https://developer.xamarin.com/api/type/MonoTouch.UIKit.IUIInputViewAudioFeedback/
You'll want something like this (untested):
public void SomeButtonFunction()
{
SomeBtn.TouchUpInside += (s, e) => {
UIDevice.CurrentDevice.PlayInputClick();
};
}

How to implement a custom presenter in a Windows UWP (Xamarin, MvvmCross)

I have the following code in my Android app, it basically uses one page (using a NavigationDrawer) and swaps fragments in/out of the central view. This allows the navigation to occur on one page instead of many pages:
Setup.cs:
protected override IMvxAndroidViewPresenter CreateViewPresenter()
{
var customPresenter = new MvxFragmentsPresenter();
Mvx.RegisterSingleton<IMvxFragmentsPresenter>(customPresenter);
return customPresenter;
}
ShellPage.cs
public class ShellPage : MvxCachingFragmentCompatActivity<ShellPageViewModel>, IMvxFragmentHost
{
.
.
.
public bool Show(MvxViewModelRequest request, Bundle bundle)
{
if (request.ViewModelType == typeof(MenuContentViewModel))
{
ShowFragment(request.ViewModelType.Name, Resource.Id.navigation_frame, bundle);
return true;
}
else
{
ShowFragment(request.ViewModelType.Name, Resource.Id.content_frame, bundle, true);
return true;
}
}
public bool Close(IMvxViewModel viewModel)
{
CloseFragment(viewModel.GetType().Name, Resource.Id.content_frame);
return true;
}
.
.
.
}
How can I achieve the same behavior in a Windows UWP app? Or rather, is there ANY example that exists for a Windows MvvmCross app which implements a CustomPresenter? That may at least give me a start as to how to implement it.
Thanks!
UPDATE:
I'm finally starting to figure out how to go about this with a customer presenter:
public class CustomPresenter : IMvxWindowsViewPresenter
{
IMvxWindowsFrame _rootFrame;
public CustomPresenter(IMvxWindowsFrame rootFrame)
{
_rootFrame = rootFrame;
}
public void AddPresentationHintHandler<THint>(Func<THint, bool> action) where THint : MvxPresentationHint
{
throw new NotImplementedException();
}
public void ChangePresentation(MvxPresentationHint hint)
{
throw new NotImplementedException();
}
public void Show(MvxViewModelRequest request)
{
if (request.ViewModelType == typeof(ShellPageViewModel))
{
//_rootFrame?.Navigate(typeof(ShellPage), null); // throws an exception
((Frame)_rootFrame.UnderlyingControl).Content = new ShellPage();
}
}
}
When I try to do a navigation to the ShellPage, it fails. So when I set the Content to the ShellPage it works, but the ShellPage's ViewModel is not initialized automatically when I do it that way. I'm guessing ViewModels are initialized in MvvmCross using OnNavigatedTo ???
I ran into the same issue, and built a custom presenter for UWP. It loans a couple of ideas from an Android sample I found somewhere, which uses fragments. The idea is as follows.
I have a container view which can contain multiple sub-views with their own ViewModels. So I want to be able to present multiple views within the container.
Note: I'm using MvvmCross 4.0.0-beta3
Presenter
using System;
using Cirrious.CrossCore;
using Cirrious.CrossCore.Exceptions;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.Views;
using Cirrious.MvvmCross.WindowsUWP.Views;
using xxxxx.WinUniversal.Extensions;
namespace xxxxx.WinUniversal.Presenters
{
public class MvxWindowsMultiRegionViewPresenter
: MvxWindowsViewPresenter
{
private readonly IMvxWindowsFrame _rootFrame;
public MvxWindowsMultiRegionViewPresenter(IMvxWindowsFrame rootFrame)
: base(rootFrame)
{
_rootFrame = rootFrame;
}
public override async void Show(MvxViewModelRequest request)
{
var host = _rootFrame.Content as IMvxMultiRegionHost;
var view = CreateView(request);
if (host != null && view.HasRegionAttribute())
{
host.Show(view as MvxWindowsPage);
}
else
{
base.Show(request);
}
}
private static IMvxWindowsView CreateView(MvxViewModelRequest request)
{
var viewFinder = Mvx.Resolve<IMvxViewsContainer>();
var viewType = viewFinder.GetViewType(request.ViewModelType);
if (viewType == null)
throw new MvxException("View Type not found for " + request.ViewModelType);
// Create instance of view
var viewObject = Activator.CreateInstance(viewType);
if (viewObject == null)
throw new MvxException("View not loaded for " + viewType);
var view = viewObject as IMvxWindowsView;
if (view == null)
throw new MvxException("Loaded View is not a IMvxWindowsView " + viewType);
view.ViewModel = LoadViewModel(request);
return view;
}
private static IMvxViewModel LoadViewModel(MvxViewModelRequest request)
{
// Load the viewModel
var viewModelLoader = Mvx.Resolve<IMvxViewModelLoader>();
return viewModelLoader.LoadViewModel(request, null);
}
}
}
IMvxMultiRegionHost
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.WindowsUWP.Views;
namespace xxxxx.WinUniversal.Presenters
{
public interface IMvxMultiRegionHost
{
void Show(MvxWindowsPage view);
void CloseViewModel(IMvxViewModel viewModel);
void CloseAll();
}
}
RegionAttribute
using System;
namespace xxxxx.WinUniversal.Presenters
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class RegionAttribute
: Attribute
{
public RegionAttribute(string regionName)
{
Name = regionName;
}
public string Name { get; private set; }
}
}
These are the three foundational classes you need. Next you'll need to implement the IMvxMultiRegionHost in a MvxWindowsPage derived class.
This is the one I'm using:
HomeView.xaml.cs
using System;
using System.Diagnostics;
using System.Linq;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.WindowsUWP.Views;
using xxxxx.Shared.Controls;
using xxxxx.WinUniversal.Extensions;
using xxxxx.WinUniversal.Presenters;
using xxxxx.Core.ViewModels;
namespace xxxxx.WinUniversal.Views
{
public partial class HomeView
: MvxWindowsPage
, IMvxMultiRegionHost
{
public HomeView()
{
InitializeComponent();
}
// ...
public void Show(MvxWindowsPage view)
{
if (!view.HasRegionAttribute())
throw new InvalidOperationException(
"View was expected to have a RegionAttribute, but none was specified.");
var regionName = view.GetRegionName();
RootSplitView.Content = view;
}
public void CloseViewModel(IMvxViewModel viewModel)
{
throw new NotImplementedException();
}
public void CloseAll()
{
throw new NotImplementedException();
}
}
}
The last piece to make this work is the way the actual xaml in the view is set-up. You'll notice that I'm using a SplitView control, and that I'm replacing the Content property with the new View that's coming in in the ShowView method on the HomeView class.
HomeView.xaml
<SplitView x:Name="RootSplitView"
DisplayMode="CompactInline"
IsPaneOpen="false"
CompactPaneLength="48"
OpenPaneLength="200">
<SplitView.Pane>
// Some ListView with menu items.
</SplitView.Pane>
<SplitView.Content>
// Initial content..
</SplitView.Content>
</SplitView>
EDIT:
Extension Methods
I forgot to post the two extension methods to determine if the view declares a [Region] attribute.
public static class RegionAttributeExtentionMethods
{
public static bool HasRegionAttribute(this IMvxWindowsView view)
{
var attributes = view
.GetType()
.GetCustomAttributes(typeof(RegionAttribute), true);
return attributes.Any();
}
public static string GetRegionName(this IMvxWindowsView view)
{
var attributes = view
.GetType()
.GetCustomAttributes(typeof(RegionAttribute), true);
if (!attributes.Any())
throw new InvalidOperationException("The IMvxView has no region attribute.");
return ((RegionAttribute)attributes.First()).Name;
}
}
Hope this helps.
As the link to the blog of #Stephanvs is no longer active I was able to pull the content off the Web Archive, i'll post it here for who ever is looking for it:
Implementing a Multi Region Presenter for Windows 10 UWP and MvvmCross
18 October 2015 on MvvmCross, Xamarin, UWP, Windows 10, Presenter > Universal Windows Platform
I'm upgrading a Windows Store app to the new Windows 10 Universal
Windows Platform. MvvmCross has added support for UWP in v4.0-beta2.
A new control in the UWP is the SplitView control. Basically it
functions as a container view which consist of two sub views, shown
side-by-side. Mostly it's used to implement the (in)famous hamburger
menu.
By default MvvmCross doesn't know how to deal with the SplitView, and
just replaces the entire screen contents with a new View when
navigating between ViewModels. If however we want to lay-out our views
differently and show multiple views within one window, we need a
different solution. Luckily we can plug-in a custom presenter, which
will take care of handling the lay-out per platform.
Registering the MultiRegionPresenter
In the Setup.cs file in your UWP project, you can override the
CreateViewPresenter method with the following implementation.
protected override IMvxWindowsViewPresenter CreateViewPresenter(IMvxWindowsFrame rootFrame)
{
return new MvxWindowsMultiRegionViewPresenter(rootFrame);
}
Using Regions
We can define a region by declaring a
element. At this point it has to be a Frame type because then we can
also show a nice transition animation when switching views.
<mvx:MvxWindowsPage ...>
<Grid>
<!-- ... -->
<SplitView>
<SplitView.Pane>
<!-- Menu Content as ListView or something similar -->
</SplitView.Pane>
<SplitView.Content>
<Frame x:Name="MainContent" />
</SplitView.Content>
</SplitView>
</Grid>
</mvx:MvxWindowsPage>
Now we want to be able when a ShowViewModel(...) occurs to swap out
the current view presented in the MainContent frame.
Showing Views in a Region
In the code-behind for a View we can now declare a MvxRegionAttribute,
defining in which region we want this View to be rendered. This name
has to match a Frame element in the view.
[MvxRegion("MainContent")]
public partial class PersonView
{
// ...
}
It's also possible to declare multiple regions within the same view.
This would allow you to split up your UI in more re-usable pieces.
Animating the Transition between Content Views
If you want a nice animation when transitioning between views in the
Frame, you can add the following snippet to the Frame declaration.
<Frame x:Name="MainContent">
<Frame.ContentTransitions>
<TransitionCollection>
<NavigationThemeTransition>
<NavigationThemeTransition.DefaultNavigationTransitionInfo>
<EntranceNavigationTransitionInfo />
</NavigationThemeTransition.DefaultNavigationTransitionInfo>
</NavigationThemeTransition>
</TransitionCollection>
</Frame.ContentTransitions>
</Frame>
The contents will now be nicely animated when navigating.
Hope this helps, Stephanvs

Resources