Xamarin Binding Title of Navigation page - xamarin

i´ve got an little problem. i got like a searchpage, and if you click on an item from the search, you will get so an other page using the navigationpage. i want the title of this page set to the clicked item. here´s what i got:
private async void PatListe_ItemTapped(object sender, ItemTappedEventArgs e)
{
if (e.Item is Patient pat)
{
PatNN = pat.NName.ToString();
PatVN = pat.VName.ToString();
PatInt = pat.Fallnummer;
}
PatVN_NN = PatNN + " " + PatVN;
await Navigation.PushAsync(new PatientView());
}
so this gives me the "name" I want for the title. with debugging and stopping-points, i noticed that this is working. now there are 2 mistakes i guess, one is on the other site in .cs and on in the .xaml file. here´s the one from my .cs-file:
private string PatNameTitle = SuchErgebnisse.PatVN_NN;
while debugging, i recognised that this does not get any value, its null. but: i´ve got the same with the PatInt and this is working...
but even if this is working, there´s an other mistake - in my xaml file:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="INESVitaAppTest.Views.PatientenView" BackgroundColor="#235d2a" Title="{Binding PatNameTitle}">
this gives me nothing even when i m using a string, like " PatNameTitle = "foo"; "
thanks a lot !

damn, i got it. There was no initialisation of the PatNameTitle....here is what i added:
Title = PatNameTitle;
in an method that get´s called when i open this page.. ant then i deleted the Title="{Binding..}"-stuff, now it s orking :) sorry

Related

developing a picker that pops out from the selected frame downward in xamarin forms

I have a design i'm trying to implement. Although I've ben working with Rg.plugin for a while trying out different animations and entry behaviour but it's always covering the whole screen.
However, the current design I'm working with is different.
here is the image
Please does anyone have an idea how I can achieve this using xamarin forms please.
Any help will be appreciated.
Note, I already have the design in place using pancakeView and Rg.plugin to pop it out on click. However, the positioning is what I haven't been able to achieve. though I've not written any code for it yet cos I prefer to do my research right.
Please I need anyone to point me to the right path or how to achieve this.
thanks in advance
According to your screenshot, you can do custom control using entry and ListView to get it, there is also one custom control that you can take a look:
Installing Xamarin.Forms.EntryAutoComplete
Uisng this custom control like:
<ContentPage
x:Class="demo3.listviewsample.Page36"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:customControl="clr-namespace:EntryAutoComplete;assembly=EntryAutoComplete">
<ContentPage.Content>
<StackLayout>
<customControl:EntryAutoComplete
ItemsSource="{Binding Countries}"
MaximumVisibleElements="5"
Placeholder="Enter country..."
SearchMode="{Binding SearchMode}"
SearchText="{Binding SearchCountry}"
VerticalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
public class dialogvidemodel:ViewModelBase
{
private string _searchCountry = string.Empty;
private SearchMode _searchMode = SearchMode.Contains;
public string SearchCountry
{
get => _searchCountry;
set
{
_searchCountry = value;
RaisePropertyChanged("SearchCountry");
}
}
public List<string> Countries { get; } = new List<string>
{
"African Union",
"Andorra",
"Armenia",
"Austria",
"Togo",
"Turkey",
"Ukraine",
"USA",
"Wales"
};
public SearchMode SearchMode
{
get => _searchMode;
set
{
_searchMode = value;
RaisePropertyChanged("SearchMode");
}
}
}
More detailed info, please take a look:
https://github.com/krzysztofstepnikowski/Xamarin.Forms.EntryAutoComplete

ZXingScannerView throws A method was called at an unexpected time caused by StopScanningAsync when navigating back

Using Xamarin Forms 3.6 with Prism, Fody and ZXing and running UWP app.
A navigation stack of MainPage/Navigation Page/ViewA/ViewB/ViewC?selectedTab=Tab3.
Tab3 has a ZXingScannerView control on it.
If I try to back button away to ViewB then the app crashes with the error 'A method was called at an unexpected time.'
The exception shows that it is trying to wait for the ZXing StopScanningAsync() method.
The page sequence is this:
MainPage which is a Master Detail showing View A initially.
View A -> View B -> View C which is a Tabbed Page
On the tab are 4 views defined as Content Pages, all navigable with Tab1 shown initially.
Tab1 is a simple data entry form
Tab2 has an input field, a button and an instance of CustomControl
Tab3 has a button,a ZXingScannerView control and an instance of CustomControl
Tab4 has a button, an Image and an instance of CustomControl
So when the user arrives at ViewC the navigation uri should be MainPage/Navigation Page/ViewA/ViewB/ViewC?selectedTab=Tab1
The problem is the back button action.
Using Prism Navigation I can trap the OnNavigatedFrom, OnNavigatingTo, OnNavigatedTo.
None of these events occur when moving between tabs.
There is a problem with the ZXingScannerView on Tab3.
I can click on each of the tabs and go forward and backward to show each page.
The back button (back to ViewB) works as long as I do NOT display Tab3 with the ZXing view. Scanning must be initiated by clicking the button so the control has IsScanning=false when the page is loaded.
If I tab to Tab3 (and any other tab before or after) and then try to back button away to ViewB then the app crashes with the error 'A method was called at an unexpected time.'
The exception shows that it is trying to wait for the ZXing StopScanningAsync() method.
The markup is this:
<Grid
HorizontalOptions="FillAndExpand"
IsVisible="{Binding IsScanning}"
VerticalOptions="FillAndExpand">
<zxing:ZXingScannerView
x:Name="zxing"
IsAnalyzing="{Binding IsAnalyzing}"
IsScanning="{Binding IsScanning}"
ScanResultCommand="{Binding OnScanResult}" />
<zxing:ZXingDefaultOverlay
BottomText="Place the red line over the barcode you'd like to scan."
HeightRequest="20"
TopText="Accepts EAN-8 or EAN-13 barcodes" />
</Grid>
And the view model code is like this:
public Tab3PageViewModel(INavigationService navigationService,
IEventAggregator eventAgregatorService,
IPageDialogService dialogService
)
: base(navigationService, eventAgregatorService)
{
_DialogService = dialogService;
this.IsScanning = false;
this.IsAnalyzing = false;
}
public void Handle_BeginScan()
{
IsScanning = true;
IsAnalyzing = true;
}
public void Handle_OnScanResult(Result result)
{
MainThread.BeginInvokeOnMainThread(async () =>
{
if (result != null)
{
var payload = new PublishedEventPayload()
{
Code = result.Text,
ViewName = this.ViewName
};
this.AgregatorService.GetEvent<FindByBarcodeEvent>().Publish(payload);
}
else
{
await _DialogService.DisplayAlertAsync("Not found", "Unfortunately the ISBN code could not be resolved. Please try again.", "OK");
}
});
}
On Tab3 I have put an OnNavigatedFrom event to ensure that IsScanning= false, but this made no difference.
The app would crash before it got to that.
Prism Navigation Service says that it will add new views to the stack when NavigateAsync() is called.
I have tried explicitly setting the full navigation path when going from ViewB to ViewC with no effect on the problem. The nav stack seems to be right when viewed.
It seems to be a navigation issue but I can't work out why the ZXing control is interferring.
Any suggestions anyone?
I'm not sure if this will help or not, but I've run into issues where ZXingScanningView does not respect setting IsAnalyzing and IsScanning when navigating. I was running into an issue that saw the camera continue to scan barcodes even after navigating from the page. It seems your view is also continuing to scan. My solution was to completely remove the ZXingScanningView in the OnDisappearing method then to re-add it in OnAppearing if needed.
Ex. I have my ZXScanningView housed in a grid that simply contains the ZXingScanningView and ZXingDefaultOverlay. When I set own my bindable property ScanningEnabled to false it will clear all children of the grid.

Xamarin XAML variable scope not working like expected

I have a really odd problem with variable scopes. A Listview named "TodoListView" is defined via xaml, and it's ItemSource populated from a SQListe database. Works. Inside the ListView I have a ViewCell to display the data row-wise.
<ContentPage ... x:Class="JanitorPro.MainPage" ...>
<StackLayout>
<ListView x:Name="TodoListView" Margin="20" ItemSelected="OnListItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Label Text="{Binding name}" VerticalTextAlignment="Center" HorizontalOptions="StartAndExpand" />
<Switch HorizontalOptions="End" IsToggled="{Binding done}" Toggled="DoneSwitchToggled"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
The codebehind looks like this (some irrelevant portions removed):
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
// load Database
TodoListView.ItemsSource = await App.TodoDatabase.GetItemsAsync("SELECT * FROM [TodoItem]");
}
async void OnReloadButtonClicked(object sender, EventArgs e)
{
Debug.WriteLine("Reload Button Click");
TodoListView.ItemsSource = await App.TodoDatabase.GetItemsAsync("SELECT * FROM [TodoItem]");
Debug.WriteLine("Reload done.");
}
async void OnListItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem != null)
{
await Navigation.PushAsync(new TodoItemPage
{
BindingContext = e.SelectedItem as TodoItem
});
}
}
private void DoneSwitchToggled(object sender, ToggledEventArgs e)
{
// TodoItem i = null;
TodoItem i = TodoListView.SelectedItem;
if (i != null)
{
Debug.WriteLine("Toggle: {0}", i.id);
}
}
}
}
The oddity has two stages. Before I inserted the DoneSwitchToggled event handler, every occurrance of TodoListView.ItemsSource got a red underline under TodoListView and a hint that "The name TodoListView does not exist in the current context". OK, I thought that VS was not smart enough to find a definition in the xaml file, because, despite of the warning, the program compiled and ran fine. TodoListView gets initialized and does correctly display the rows of the underlying database, so it does clearly exist at runtime.
Things went wild when I added the DoneSwitchToggled event handler to both XAML and the codebehind. All the sudden the program won't compile any longer but bail out with a CS0103 error "The name "TodoListView" does not exist in the current context". The error appears three times, with the line numbers pointing to the other occurrances of TodoListView in onAppearing() and OnReloadButtonClicked(). Huh? How the heck can the addition of a variable reference in an event handler render that variable invalid in completely different methods? OK, there was something fishy with the variable before (still don't know what ...), but it worked. Now it doesn't any more, whch doesn't make any sense for me. Furthermore, if I comment out the offending line in the DoneSwitchToggled event handler, and insert a dummy definition for i, like so:
TodoItem i = null;
// TodoItem i = TodoListView.SelectedItem;
everything is like before, VS still underlines the other appearances of TodoListView, but now the program builds and runs ok again.
Anyone who can explain this effect, and show me how correct my code? I think the objective is clear: DoneSwitchToggled is supposed to write back the switch value into the database (and do some other processing not shown in my stripped down sample), and though the "sender" object is correctly set to reference my button, I found no way to access the underlying data binding, since ToggledEventArgs unfortunately does seem to only pass the switch position "true" or "false", but - unlike the OnListItemSelected event handler - not pass any reference to the bound row through the second argument. So my idea was to use ListView.SelectedItem for this purpose.
Finally I figured it out myself. This seems to be a glitch in VS 2017. There is nothing wrong with TodoListView, so error CS0103 is misleading nonsense.
What VS really means is an error CS0266. TodoListView is defined by a generic list
List<TodoItem>
to access SelectedItem i need to typecast it:
TodoItem i = (TodoItem)TodoListView.SelectedItem;
This added, all errors are gone, app code builds OK.
Btw, unfortunately this approach to get at the item where the Switch has been flipped has proven not working, TodoListView does always return null for SelectedItem, seems that the ListView control doesn't see the button press. Need to find a different way to find the list item beneath the switch to get at the bound row id.

Multiple picture boxes in multiple tab pages

I have one tabcontrol on a form with two tabpages and two picture boxes in each. I use rightclick to open a context menu for selecting a file to display in each picturebox. When I do it with one picturebox it is OK. However, after selecting a file for other picturebox fails with an exception "Parameter not valid".
Basically, I do this:
System::Void DPrint::Form1::toolStripMenuItem1_Click(System::Object^ sender, System::EventArgs^ e)
{
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
if (imgToDisplay != nullptr)
{
delete imgToDisplay;
}
PictureBox^ MyPictureBox = safe_cast<PictureBox^>(this->contextMenuStrip2->SourceControl);
imgToDisplay = gcnew System::Drawing::Bitmap(this->openFileDialog1->FileName);
MyPictureBox->Image = safe_cast<Image^>(imgToDisplay);
}
}
Any idea what is wrong? Thank you so much.
Solved.
I was deleting the last image to be displayed so I have removed an if statement
and everything works. Thank you.

How to pass a parameter in a button and get value in the code behind to redirect to another page based on the value of parameter in windows phone 7?

I am thinking if the windows phone 7 button event is similar to ASP.NET development with C#, something like in the button, I set value to commandparameter in the XAML, and in the code behind, I get the commandparameter and redirect the page.
I haven't found any good examples for button event handling, any suggestions?
Thank you.
For the xaml:
<Button Tag="pageAddress" Click="Button_Click" />
And then on the code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button _button = (Button)sender;
NavigationService.Navigate(new System.Uri(_button.Tag.ToString()));
}
I would recommend you use a command parameter as you mentioned. So in your xaml do something like this:
<Button x:name="myButton" CommandParameter="{Binding Title}" Click="myButton_Click"/>
And in your C# code something like this:
private void myButton_Click(object sender, RoutedEventArgs e)
{
Button _myButton = (Button)sender;
string value = _myButton.CommandParameter.ToString();
}
Really it's pretty similar to Teemu's answer although I must admit I haven't used the Tag
element before. According to the documentation on MSDN, the Tag element should work pretty nicely as it can store custom information that you can access in your code behind (or viewmodel).

Resources