Change main page of TabbedPage, Xamarin.iOS
I want to set the Heart screen as the first shown page when entering the whole TabbedPage, I would be happy if anyone can help me with that. Thanks
Each icon is a blank content page title:
1 answer
-
answered 2022-05-06 06:41
Liyun Zhang - MSFT
You can set the current page as the page you want in the construction method of the tabbedpage. Such as:
public TabbedPage1() { InitializeComponent(); this.CurrentPage = Children[2]; }
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
Flyout for autocomplete in WinUI 3 TextBox
Can anyone explain what the ProofingMenuFlyout is for in WinUI 3 on a TextBox? The documentation for it is bare with no example on how to use it.
What I'm actually trying to do is create a popup menu much like the auto suggestion popup in the Visual Studio text editor that gives hints on methods etc. I.e. the one you can open with Ctrl+Space. I want this functionality inside a TextBox as a helper for when certain initial letters are written.
My initial though was to use some dynamic flyout that is opened from a TextChanged callback when a keyword is detected. Then I found this ProofingMenuFlyout that is rather undocumented and I can't figure out how to use, or what it is for.
Am I on the right track with using a menu flyout or should I consider some other way of doing it?
-
Async task getting value off of JSON return, XAML/WPF app
I am trying to get a single value off of a JSON return.
My call is doing an
HttpClient
call to a webservice, it returns me my Json object. I need to now get a value off of the Json return in my class so I can pass it to another method in my class as a parameter.Current code:
var url = "https://localhost:9999/create_payment_intent"; var terminalAmount = new PaymentIntentCreateRequest(); terminalAmount.Amount = "2300"; var json = JsonConvert.SerializeObject(terminalAmount); var data = new StringContent(json, Encoding.UTF8, "application/json"); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.PostAsync(url, data); //The resulting response if (response.IsSuccessStatusCode) { var paymentIntentResponse = response.Content.ReadAsStringAsync().Result; var jsonObject = JsonConvert.DeserializeObject<object>(paymentIntentResponse.ToString()); //jsonObject returns some values {"id": "pi_xxxxxxxxx", some other data.....} // PaymentIntentId = jsonObject.Id; // I NEED THE ID VALUE OFF OF THE JSON OBJECT //PaymentIntentId = result.Id; //Call next function if result has an ID if not jump out and try again or return error } //Successful payment intent ready? //pass the payment intent amount to the variable //await response; Console.WriteLine(response); }
-
WPF Textbox Validation Error binded to Variable
In a .xaml file, I have a number of Textbox objects that are linked to data paths as such:
<TextBox Text="{Binding Path=Var1}">
These variables (like Var1) are all linked to double values, and as such, if a user attempts to input a non-double value like a string or an empty value, the box is highlighted red. I assume this is the default validation error.
I'd like to know if it's possible to set a boolean to true in my code-behind whenever one of these Textbox objects are highlighted red, and then set back to false when it's not highlighted red. In other words, I'd want to set the boolean to true whenever a user causes the default Textbox validation error, and to false when the error is resolved.
Additionally, I notice that this validation error fires off when the Textbox loses focus; i.e. when the user clicks off of that Textbox or moves to a different Textbox. Is it possible for the validation error to fire off on each keystroke instead?
Thanks. I'm something of a WPF beginner, but it's been hard to find specifics about my issue, and I suspect it'll be useful information to understand data validation down the road.
-
Change item control property of checked listview item Xamarin.Forms
Hy, I am trying to show a comment input if the item checkbox is checked and hide it else, i have this XAML
<ListView ItemsSource="{Binding TaskItems}" x:Name="TasksItems" HasUnevenRows="True" VerticalScrollBarVisibility="Default" SelectionMode="None"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout IsVisible="True" Orientation="Vertical"> <Grid BackgroundColor="White"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="auto" /> </Grid.RowDefinitions> <StackLayout Grid.Column="0" Grid.Row="0"> <input:CheckBox Type="Box" IsChecked="{Binding TaskChecked , Mode=TwoWay}"/> </StackLayout> <StackLayout Grid.Column="0" Grid.Row="1" IsVisible="{Binding CommentRequired}"> <Entry BackgroundColor="White" PlaceholderColor="Black" HeightRequest="40" TextColor="Black"/> </StackLayout> </Grid> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate>
and i have this c# code to read the items from database
public class TaskData { public bool TaskChecked { get; set; } public bool CommentRequired { get; set; } } public partial class HomePage : ContentPage { public HomePage() { ObservableCollection<TaskData> TaskItems { get; set; } ObservableCollection<TaskData> TasksList; TaskItems = new ObservableCollection<TaskData>(); //Loop the tasks from database result While... TaskItems.Add(new TaskData { TaskChecked = false, CommentRequired = false, }); //End Loop TasksListView.ItemsSource = TaskItems; } }
Now i need to add a "CheckChanged" event to show the comment Entry (IsVisible="True") when the user check the checkbox of the targed listview item
Thanks
-
Uploading Image files from Xamarin App to Gallery and Azure
I am working on a development (Android, IOS) that requires uploading Images files to an Azure Storage, this images can be taken from the gallery or with the device's camera.
For this I have implemented the following:
-Image Capture (I'm using Xamarin.Essentials.CapturePhotoAsync()) (Solved) -Images from Gallery (I'm using Xamarin.Essentials.PickPhotoAsync()) (Solved)
Both actions are stored in a List that will finally uploaded to the azure storage.
First question: Is this the best "approach" to upload files to storage? Is there a better practice than storing all this information in a list and finally uploading it?
In addition to this, I have a new requirement and that is that the captured images can be stored in the device's gallery. Hence my second question....
Which is the best way to get it to work on both Android and IOS? Tried some methods, but not everything works properly...
The libraries that can possibly solve this are a bit outdated or don't work in all cases....
(Xam.Plugin.Media) Have some issues on resent Android devices (Xamarin.MediaGallery) works great on Android but on IOS it's another story 😕 Dependency Services: it is the most successful and a different angle than nugets but... it currently has some things deprecated like storage routes in Android for save in Gallery....
I would appreciate your recommendations.
-
Put an image from camera with migradoc or pdfsharp with xamarin forms
I have a problem that I can't put an image from the camera to the pdf. It put the same error
"Image could not read"
. How can I do it? This is the path they gave me when I take a photo ="/storage/emulated/0/Android/data/com.companyname.atecresacalculator/files/Pictures/fotoparapdf_12.jpg"
code from CompartirInformacion(SharedInformation):
namespace AtecresaCalculator.Service { public class CompartirInformacion { public static string x; public static string y; } }
where I added into the pdf:
Row row = table.AddRow(); table.Rows.HeightRule = RowHeightRule.Auto; row.Cells[0].AddParagraph(text); row.Cells[0].VerticalAlignment = VerticalAlignment.Center; row.Cells[1].AddParagraph(texto); row.Cells[1].AddImage(FromFile(CompartirInformacion.y)); row.Cells[1].VerticalAlignment = VerticalAlignment.Center;
Clicked to take the photo:
private async void sacarFoto_Clicked(object sender, EventArgs e) { await CrossMedia.Current.Initialize(); if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { await DisplayAlert("Error en la cámara", "Activa los permisos para usar cámara", "Ok"); return; } var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { PhotoSize = Plugin.Media.Abstractions.PhotoSize.Small, Name = "fotoparapdf.jpg", CompressionQuality = 100, DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Rear, }); if (file == null) return; await DisplayAlert("Ruta de la foto", file.Path, "Ok"); CompartirInformacion.y = file.Path; }
-
Xamarin MAUI application not shows correct output
I have downloaded Visual Studio 2022 Professional (preview) version from MS Document. Also I have followed the other steps to create first sample application using .Net MAUI template after VS installed.
It does create new project with all the required dependency. I have installed Android sdk api v30 and created a simulator as mentioned in the official document.
When I have run the application on Android Emulator it does take a lot time to run and after it loaded properly it shows wrong output. It's just showing two Hello World label, while MainPage.xaml does have button as well but that button is not displayed. I have attached output screenshot here:
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MauiApp1.MainPage"> <ScrollView> <VerticalStackLayout Spacing="25" Padding="30"> <Label Text="Hello, World!" SemanticProperties.HeadingLevel="Level1" FontSize="32" HorizontalOptions="Center" /> <Label Text="Welcome to .NET Multi-platform App UI" SemanticProperties.HeadingLevel="Level1" SemanticProperties.Description="Welcome to dot net Multi platform App U I" FontSize="18" HorizontalOptions="Center" /> <Label Text="Current count: 0" FontSize="18" FontAttributes="Bold" x:Name="CounterLabel" HorizontalOptions="Center" /> <Button Text="Click me" FontAttributes="Bold" SemanticProperties.Hint="Counts the number of times you click" Clicked="OnCounterClicked" HorizontalOptions="Center" BackgroundColor="Orange" TextColor="White"/> <Image Source="dotnet_bot.png" SemanticProperties.Description="Cute dot net bot waving hi to you!" WidthRequest="250" HeightRequest="310" HorizontalOptions="Center" /> </VerticalStackLayout> </ScrollView> </ContentPage>
Does anyone know what is wrong here in the app? I have followed the steps mentioned in the MS Document which I have mentioned in the question.
-
How to get selected item in Xamarin
I have a Picker in Xamarin and I want to pass the selected item in Picker to the another page(TablePage). Below this Picker there is a button and whenever it is clicked I want to go to the other page and display the selected value in the pther page.
<Picker x:Name="SelectTablePicker" Title="Select table" TextColor="#676FA3" TitleColor="#676FA3" FontSize="Title" ItemsSource="{Binding TablesFromViewModelCollector}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedTable}" /> <Button x:Name="SelectTableButton" Text="Select Table" HorizontalOptions="Center" Style="{DynamicResource TitleStyle}" Clicked="Selected_Button" />
So how I am trying to pass this value is with click event:
async void Selected_Button(object sender, System.EventArgs e) { var SelectTablePicker = (Picker)sender; int selectedIndex = SelectTablePicker.SelectedIndex; if (selectedIndex != -1) { await Navigation.PushAsync(new TablePage((string)SelectTablePicker.ItemsSource[selectedIndex])); } }
And on the Table Page, I created Label where I want to show the selected item:
<Label x:Name="MyLabel" Text="#" HorizontalOptions="Fill" Grid.Column="0" BackgroundColor="#FF5959" TextColor="#EEF2FF" HorizontalTextAlignment="Left" Padding="0, 0, 0, 10" VerticalTextAlignment="Center"/>
And here its controller:
public TablePage(string tableName) { InitializeComponent(); MyLabel.Text = $"{UserName}"; }
But whenever I click the button I am getting an error and I couldnt figure out why.
-
Xamarin.Forms: Display additional tab on specific Platform
Good morning
I have a TabbedPage in my application. Due to restictions I would like to display one more tab on Android than on iOS.
My current TabbedPage look like:
<TabbedPage> ... <ContentPage x:Name="Page1"/> <ContentPage x:Name="Page2"/> <ContentPage x:Name="Page3"/> <ContentPage x:Name="Page4"/> </TabbedPage>
I have decided to render Page3 only for Android. I changed my code into:
<TabbedPage> ... <ContentPage x:Name="Page1"/> <ContentPage x:Name="Page2"/> <OnPlatform x:TypeArguments="Page"> <On Platform="Android"> <On.Value> <ContentPage x:Name="Page3"/> </On.Value> </On> </OnPlatform> <ContentPage x:Name="Page4"/> </TabbedPage>
This leads to runtime exception when entering into this TabbedPage:
An error occurred: 'Value cannot be null. Parameter name: item'. Callstack: ' at Xamarin.Forms.ObservableWrapper`2[TTrack,TRestrict].Add (TRestrict item) [0x00008] in D:\a\1\s\Xamarin.Forms.Core\ObservableWrapper.cs:27
I tried to remove x:Name but did not work. Any ideas?
PS. As a workaround I am always able to:
Constructor() { if(Runtime.IsIOS) { this.Children.Remove(this.Page3) } }
However would be better to not render it at all and have it at XAML level.
-
Xamarin.Forms TabbedPage - iOS with 'More..' tabitem
Good morning
I have created a TabbedPage where untill now I had 4 tabs. Everything was working as expected however I have to add two more tabs and the problem begins.
On Android platform result is as expected. I do contain two more TabBarIcon on my TabBar. However on iOS instaed of having two TabBarIcons, I have one additional whch is called "More" and there by design of iOS I have DropDown to pick which I wanna select.
I wonder if there is any option to avoid the 'More' button and keep having six tabs.
I was looking around the interent but couldn't find any custom renderer for iOS.
Is is possible ?
-
How to use bottom tabitems combined with a flyoutpage in Xamarin Forms?
I currently have a flyoutpage.
Code:
<FlyoutPage.Flyout> <views:MenuPage /> </FlyoutPage.Flyout> <FlyoutPage.Detail> <NavigationPage> <x:Arguments> <views:TrainingPage /> </x:Arguments> </NavigationPage> </FlyoutPage.Detail>
However I also want to have tabitems at the bottom. Is this possible in Xamarin Forms?