Hiding a tab in Xamarin.Forms using Prism framework - c#

I am working on a Xamarin Forms project that uses an MVVM pattern and Prism.
My issue is, I need to be able to hide a tab on a tab page based off of a bool. There is a bindable property in the XAML called "IsVisible", which I assumed would hide the tab from the user, but instead the tab still shows but displays a blank page when selected.
Currently my XAML looks like this
<?xml version="1.0" encoding="utf-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
xmlns:local="clr-namespace:com.XXXXXXX"
prism:ViewModelLocator.AutowireViewModel="True"
BackgroundColor="White"
x:Class="com.XXXXXXXXXX.EditChargePage"
Title="{Binding Title}">
<local:EditChargeDetailsPage Title="Details" />
<local:EditChargeTrackingPage Title="Tracking" IsVisible="{Binding TabContext.HasTracking}" IsEnabled="{Binding TabContext.HasTracking}"/>
<local:EditChargeNotesPage Title="Notes" />
</TabbedPage>
Originally to solve the problem I just used "IsVisible", when that didn't work as expected I added "IsEnabled" which didn't seem to do anything.
Is there a way to hide the Tab from the UI using a boolean value in Xamarin (or Prism for Xamarin) without breaking MVVM?

You might want to check out the Prism Samples. The TabbedNavigation sample demonstrates how to initialize your tabbed children with INavigatingAware or the IEventAggregator, as well as dynamically adding the tabs at run time. If you need even finer control, such as a value in a ViewModel of one of your Child Pages that determines whether some other page should be shown, then you could use this to publish an event with the IEventAggregator and subscribe to that event in your TabbedPage to handle adding or removing the page.
Unfortunately IsVisible and IsEnabled do not actually work within a TabbedPage the way you were hoping. So the only way you can accomplish this is to actually manipulate the Children of the TabbedPage directly pushing or popping them from the collection.

Related

Prism View is being assigned parent page ViewModel inside XCT tabview

I have historically been using the syncfusion tab control as part of my layout on my apps, however, with the recent introduction of the Xamarin Community Toolkit (xct) and with the LazyView being in the latest pre-release nuget I want to use this and see what the experience is like.
I perform the registration as normal in the app.xaml.cs file as I always do:
ViewModelLocationProvider.Register<HomeView, HomeViewViewModel>();
When I am on my content page I add the view to a tab item:
<xct:TabViewItem Icon="{AppThemeBinding Light={local:ImageResource App.Assets.Icons.Black.home_100px.png}, Dark={local:ImageResource App.Assets.Icons.White.home_100px.png}}" Text="Home">
<xct:TabViewItem.Content>
<xct:LazyView x:TypeArguments="dressmakerViews:HomeView" />
</xct:TabViewItem.Content>
</xct:TabViewItem>
At this point the view is added as expected but is assigned the viewmodel of the contentpage instead of the viewmodel I registered for the view.
Obvious troubleshooting here was to use LazyView outside of the tabview and that assigned the expected viewmodel.
My question here is to help me understand why it does this and how to resolve the problem.
As a workaround to get the app working I've had to move out the code into the view model for the content page but everything here feels wrong and I want to be in a position to resolve.
For some reason, TabView replaces any previous BindingContext values assigned to TabItems with its own BindingContext when it changes..
As a work-around you can add a listener to BindingContextChanged event for each TabViewItem.Content and reassign to its expected ViewModel.
UPDATE:
You can also wrap TabView's Content with a ContentView
<xct:TabViewItem Icon="{AppThemeBinding Light={local:ImageResource App.Assets.Icons.Black.home_100px.png}, Dark={local:ImageResource App.Assets.Icons.White.home_100px.png}}" Text="Home">
<xct:TabViewItem.Content>
<ContentView>
<xct:LazyView x:TypeArguments="dressmakerViews:HomeView" />
</ContentView>
</xct:TabViewItem.Content>
</xct:TabViewItem>
That way, LazyView's BindingContext won't be overwritten.

Best practice for choosing handler or command for the button in Xamarin.Forms

I'm new in Xamarin. By learning the MVVM pattern, I've got the idea for mapping button with commands, and deal with logical things in viewmodel.
Then scenarios changed.
When I was developing some Login functionalities for the mobile app, I need to call "DisplayAlert" or "pop" or "push" when clicking the button.
I checked some forums and blogs to see how to solve, listed as below:
pass the navigation as a parameter, like this thread, or even use injection in the same thread;
use NuGet packages like userdialogs
use handler like Microsoft docs, (so I assumed that it is acceptable to use handler in simple navigation).
add some message text in viewmodel class and mapping to some entries on the view, but this cannot solve the conflict when it is required for a dialog box or navigation.
So is this question supposed to change to "how to choose button implementation, handler or command"?
But again, "handler" is not recommended by MVVM. Now I am confused.
Any advice will be helpful.
Cheers.
Though you have used MVVM .Use command is better because it will break the standard of MVVM (we should handle the logic in ViewModel as soon as possible) if you use click event in code behind.
You can handle the logic in ViewModel and pass params in xaml .
For example , if you want pass the content page and get the navigation in ViewModel
in xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="MainContentPage"
x:Class="xxx.MainPage">
//...
<Button Command="{Binding Path=BindingContext.ButtonClickCommand , Source={x:Reference MainContentPage}}" CommandParameter="{Binding .}" Text="xxx"/>
...
in ViewModel
ButtonClickCommand = new Command(
(parameter) =>
{
var page = parameter as ContentPage;
// do something you want
});

Coding a Navigation Drawer Menu (Slider Menu). (Master Page Detail)

Trying to build a Slider menu I´m using this docu coming from official Xamarin.
MasterPageDetail
Quite odd, it´s not working. VS2015 intellense recognized me MasterDetailPage (my class is inheriting from it), but when I´m trying to launch the app, next error appears:
The type or namespace name 'MasterPageDetail' does not exist in the namespace 'Xamarin.Forms' (are you missing an assembly reference?)
What it happens? Do you know of any simply working demo?
I´m using this question as reference, but I´m not getting it works...
Slider
Some answer uses MasterPageDetail, another one implemented the solution in app (class) and I need to do it in a ContentPage
Thanks mates.
EDITED: I´m using Xamarin.Forms and I imported it and I don´t have any class called like this (MasterPageDetail)... Quite odd, it sounds like a stupid thing but I can´t see it.
MasterDetailPage is class from Xamarin.Forms if you have class with the same name then it may be a conflict.
Here are some useful links:
https://developer.xamarin.com/guides/xamarin-forms/user-interface/navigation/master-detail-page/
https://developer.xamarin.com/api/type/Xamarin.Forms.MasterDetailPage/
You can also download my Example from my Github:
https://github.com/15mgm15/XamarinForms-MasterDetailPage-Recipe
There's a simple way to create a MasterDetailPage using XAML, first of all you need to create a page which will contains the MasterDetailPage and a SecondPage which will contains a DetailPage, by doing this, you need to change your hierarchy of this page to MasterDetailPage, and finally load a SecondPage inside of MasterDetailPage.
In your project Create a New Page - MenuPage and change the Page Type ContentPage to MasterDetailPage
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
BackgroundColor="White"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourProject.MenuPage">
</MasterDetailPage>
Then go to your MenuPage.cs and change the hierarchy to MasterDetailPage too.
public partial class MenuPage : MasterDetailPage
{
public ChatPage()
{
InitializeComponent();
}
}
Go back to your XAML page - MenuPage and add this :
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourProjectName.MenuPage">
<MasterDetailPage.Master>
<ContentPage Title="Menu">
<StackLayout Orientation="Vertical">
<!--Here goes your Menu Items-->
<Button Text="MyFirstButton"/>
<Button Text="MySecondButton"/>
<Button Text="MyThirdButton"/>
</StackLayout>
</ContentPage>
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<local:SecondPage/>
</MasterDetailPage.Detail>
</MasterDetailPage>
And finally you need to add a reference to your DetailPage
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourProjectName.MenuPage"
<!-- Add this line to refer your DetailPage, `SecondPage`-->
<!-- put your namespace and repeat in assembly -->
xmlns:local="clr-namespace:YourProjectName;assembly=YourProjectName">
</MasterDetailPage>
I hope its helps you!
I got it.
Finally I clean all project and started a code from zero using the next example (adding just MasterPageItem.cs, piece of cake):
Working MasterDetailDemo
I improved the demo by my own, creating a Master Page Detail where Master´s items bind specific generic page, it will be fill with its own attributes whose depends of id passed to the page´s constructor.
Github Slider Menu improved demo
Hoping it helps...

Use SendKeys in a UserControl

I want to use the C# System.Windows.Forms.SendKeys.SendWait() Method to send Keystrokes from an OnScreenKeyboard to a Textbox. Since I may use this OnScreenKeyboard at other places too I created a UserControl with View (for the Design of the Keyboard) and Viewmodel (basically for calling the Sendkeys.SendWait() Method) in an extra project.
Within this project I created a MainView where I included the UserControl via a ContentControl as you can see in the Code below. CurrentPage basically refers to the Viewmodel of the Keyboard.
<Window.Resources>
<DataTemplate DataType="{x:Type viewModel:KeyboardViewmodel}">
<view:KeyboardView/>
</DataTemplate>
</Window.Resources>
<Grid>
<Border Background="White">
<HeaderedContentControl Content="{Binding Path=CurrentPage}"/>
</Border>
<TextBox Width="120"/>
</Grid>
I now have the OnScreenKeyboard and a Textbox in my Window. Clicking into the Textbox and pressing buttons of my OnScreenKeyboard will result in text appearing in my Textbox. All Controls within the KeyboardView are set to avoid getting focus. This is necessary to maintain focus on the Textbox.
The Buttons in the KeyboardView all bind to the Command ClickCommandin my KeyboardViewmodel. Here is the code of the KeyboardViewmodel:
public class KeyboardViewmodel : BaseModel
{
public BaseCommand ClickCommand { get; set; }
public KeyboardViewmodel()
{
ClickCommand = new BaseCommand(PressAndRelease);
}
public void PressAndRelease(object key)
{
if (((string)key).Length <= 1)
SendKeys.SendWait((string)key);
else
SendKeys.SendWait("{" + (string)key + "}");
}
}
Now I did create a NuGet Package with these Files and imported them to the project where I want to use my OnScreenKeyboard.
I did do basically the same as when I tested the OnScreenKeyboard before.
But let me explain the structure of the project a little more:
I have a MainView + MainViewmodel. The MainViewmodel manages the navigation between available pages. To show these pages I have - as in the short example before - a ContentControl whose content is bound to a CurrentPage Property. The MainViewis a normal Window, all other Views are UserControls.
In one of these pages I need an OnScreenKeyboard (DetailsView + DetailsViewmodel). So it seemed logical to me to use another ContentControl within the DetailsView:
<Border Grid.Column="0" Grid.Row="4" Grid.ColumnSpan="3" Height="Auto" Width="Auto">
<ContentControl Content="{Binding Path=OnScreenKeyboard}"/>
</Border>
I create the KeyboardViewmodel in the constructor of the DetailsViewmodel. The constructor of the DetailsViewmodel is called in the MainViewmodel at startup.
So now everything works out fine so far, the OnScreenKeyboard is shown on the correct page in the correct place. If I click a button of the OnScreenKeyboard the proper bound command is called and the SendKeys.SendWait() Method is called.
But no text appears in the TextBox. I have a very bad understanding of the SendKeys.SendAwait() Method. Also, the MSDN Documentation seems to be not very exhaustive on this topic.
It states: "Sends the given keys to the active application, and then waits for the messages to be processed."
Now. The Active / Focused Application is my Application. So my guess is that the KeyStrokes should be processed by my Textbox.
My Questions:
Any guesses how to debug the 'SenWait()' Method further e.g. track where the strokes are really sent to or something like that?
Is this the correct way for sending KeyStrokes to an active Application? It seems like SendKeys comes from Windows Forms, I use WPF.
Should I just pass my Textbox as reference to the OnScreenKeyboard and write directly to the referenced Textbox? This would make me much less flexible in regards of reusability.
Update:
As pointed out in the comments this could probably be a duplicate question.
I am well aware of the various different solutions and have already considerd them:
http://wpfkb.codeplex.com/
http://www.codeproject.com/Articles/32568/A-Touch-Screen-Keyboard-Control-in-WPF
http://www.codeproject.com/Articles/145579/A-Software-Virtual-Keyboard-for-Your-WPF-Apps
But as one may understand these projects are looking all way too powerfull for my simple needs.
Here a screenshot to provide a better understanding of my needs:
It is really as simple as that. 4 rows of buttons that will never change, no other controls / functionality than sending the CommandParameter of the pressed button to the Textbox / Active Form.
Researching on that specific problem hasn't shown any problems like that. In most other SO Questions the problem is to send Data to another Window, not to send Data WITHIN the current Window.
So I don't consider this question as duplicate.

Change a section of a window upon click event

I have a treeview at the left side of the screen, and when I click on any of the TreeViewItem, I want the right side of the screen to change accordingly.
For example, clicking on 'Project' would display on the right half of the screen, a label for project name along with the project name in a text box, and a similar label-textbox pair for some other fields. Clicking on a sub-option of 'Project' such as 'Task 1' should change the right half of the screen such that instead of labels and textboxes for project name and details, it should now be for task name/details. Atm, I only care about label-textbox pairs but in the future I'll need some more sophisticated options, maybe buttons and tables.
What I thought of was to have a grid premade for each option, when I clicked on 'Project' there would be a grid which displays all the info for a Project. And when I then clicked on 'Task 1', the Project grid should be hidden and the Task grid should be displayed with the fields filled out.
Is this possible? What should I be using to create templates that I can then choose from?
Firoz already mentioned the important bit. A rough guess is that you're not using MVVM pattern, so to minimize the adaption effort, you could add a Content Control to your window and set the content of this control whenever a selection is made. You can put any User Control in there.
Using MVVM would mean you bind that Content Control to a property on your ViewModel (of type UIElement or UserControl) and set an instance whenever a bound selected values changes. Speaking of selected Value, I think the default TreeView is not really Binding-friendly, so you might end up with behaviours that do the binding for you.
What you are asking to do is quite easy and possible, but I don't think you are thinking quite big enough.
As your project grows and the number of different things that you want to show expands, then you are going to need to show and hide more and more controls. This is quite quickly going to get unmanageable. Instead think about some other controls deal with this, in some ways you are doing something very like a tabbed dialog, just with a hierarchical set of tabs.
A tabbed dialog has a panel and a set of tabs, when you click on each tab, the content of the panel changes. In fact you can create UserControls one for each specialised set of UI that you want to display, e.g. you could have a ProjectControl that displays all of your project textboxes, labels, buttons etc.
In addition WPF has this neat feature called DataTemplates, these define how a type of data should look when it is displayed. So if you where to have a
public class MyProject
{
public string Name {get;set;}
}
Then you could define
<DataTemplate DataType="{x:Type MyProject}>
<TextBox Text="{Binding Name}"/>
</DataTemplate>
And WPF will automatically convert the data into to its visual form if you set it as the content of the tab panel.
However this type of displaying content in a panel is not the only WPF control that does this. There is also something called a NavigationFrame, which also can be used wrapped into a Window as a NavigationWindow. This control provides you ways to navigate to the next Page to display. Pages can be just like the UserControls in a tabbed dialog, but can also be URIs, enabling you to link in content from the web if you wish. In addition you can call NavigateTo from other controls enabling you build much more usable interfaces.
I worked through the process of building a full windows control panel style interface in
http://alski.net/post/2012/01/11/WPF-Wizards.aspx
and http://alski.net/post/2012/01/13/WPF-Wizards-part-2-Glass.aspx
I've added later VS2012 style glows in
http://alski.net/post/2013/09/14/WPF-Re-creating-VS2012Office-2013-window-glow.aspx
And then released the entire source code as open source at
http://winchrome.codeplex.com/
This comes with support for embedding Navigation panels with
<WinChrome:SearchableNavigationWindow
x:Class="WinChrome.Win7Demo.MainWindow"
...
xmlns:WinChrome="clr-namespace:WinChrome;assembly=WinChrome"
Style="{StaticResource Win7NavigationWindow}">
<WinChrome:SearchableNavigationWindow.Navigation>
<view:Navigation x:Name="navigationTree"/>
</WinChrome:SearchableNavigationWindow.Navigation>
(Full source code)
Where the navigation window is embedded as, but can also be a TreeView.
<UserControl x:Class="WinChrome.View.Navigation" ...>
<ScrollViewer HorizontalScrollBarVisibility="Disabled" Padding="12,0"
VerticalScrollBarVisibility="Auto" >
<StackPanel>
<Button
Margin="0,12,0,0" Style="{StaticResource LinkNavigatorButtonStyle}"
Content="Home"
Command="{Binding
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Win7Demo:MainWindow}, AncestorLevel=1},
Path=GoHomeCommand}" />
</StackPanel>
</ScrollViewer>
(Full source code)

Categories