Creating a Popup in .Net Maui but "InitializeComponent()" ist not being recognized - c#

I want to create a Popup with two Buttons. I have actually created other Popups just like this before but this time it doesn't work because the InitializeComponent() method does not exist in the current context.
C#-Code:
using CommunityToolkit.Maui.Views;
using SiRiAs.Lib.Helpers;
namespace SiRiAs.Views.Popups;
public partial class DeletePopup : Popup {
public DeletePopup() {
InitializeComponent();
}
private void Delete_Clicked(object sender, EventArgs e) => Close(DeletePopupResult.Delete);
private void Keep_Clicked(object sender, EventArgs e) => Close(DeletePopupResult.Keep);
}
Xaml:
<toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Class="SiRiAs.Views.Popups.DeletePopup">
<StackLayout>
<StackLayout Padding="15" Spacing="20">
<Button Style="{StaticResource BaseButtonStyle}"
Text="Ja,löschen"
Clicked="Delete_Clicked"
/>
<Button Style="{StaticResource BaseButtonStyle}"
Text="Nein, nicht löschen"
Clicked="Keep_Clicked"
/>
</StackLayout>
</StackLayout>
</toolkit:Popup>
I don't see, that I am doing anything different then written in the Documentation: https://learn.microsoft.com/de-de/dotnet/communitytoolkit/maui/views/popup
Also If I look up InitializeComponent() in the other Popups, it brings me to a file, that I cannot added, that is auto-generated.
The auto-generated file of another Popup, the MoreOptionsPopup, just as a reference with what I mean by auto-generated file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a .NET MAUI source generator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Microsoft.Maui.Controls.Xaml.XamlResourceId("SiRiAs.Views.Popups.MoreOptionsPopup.xaml", "Views/Popups/MoreOptionsPopup.xaml", typeof(global::SiRiAs.Views.Popups.MoreOptionsPopup))]
namespace SiRiAs.Views.Popups
{
[global::Microsoft.Maui.Controls.Xaml.XamlFilePath("Views\\Popups\\MoreOptionsPopup.xaml")]
public partial class MoreOptionsPopup : global::CommunityToolkit.Maui.Views.Popup
{
[global::System.CodeDom.Compiler.GeneratedCode("Microsoft.Maui.Controls.SourceGen", "1.0.0.0")]
#if NET5_0_OR_GREATER
#endif
private void InitializeComponent()
{
global::Microsoft.Maui.Controls.Xaml.Extensions.LoadFromXaml(this, typeof(MoreOptionsPopup));
}
}
}
I tried building the project and closing VisualStudio, switching branches. I must oversee something but I don't know what and where.
I appriciate the help.

So, I tested your code. Now I am 100% sure everything is ok.
(I trust you have .UseMauiCommunityToolkit() in your MauiProgram.cs)
Most people forget to set Build Actions of their XAML file. You can:
Right click on XAML > Properties > Build Action MauiXaml.
Remove the file from the project and re-add it. (It will default to that build action)

I copied your code to my app and did a test on my android emulator, but it works well on my side.
You can try to delete the bin folders and the obj folders and rebuild it. If it doesn’t work,try to restart the Visual Studio.
Or you can create a new demo and copy your code to this new demo and try again.

Related

make on button click action for first time in Xamarin (C# and xaml file)

this is my first time to start coding in mobile app (Xamarin) using C# and I'm trying to create button when I click it, Message Appear with some Information's I wrote this code in .xaml file :
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.MainPage">
<ContentPage.Content>
<StackLayout>
<Button Text="click Me"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Center"
Clicked="OnButtonClicked"/>
<Label x:Name ="lblMessage" FontSize="Large"></Label>
</StackLayout>
</ContentPage.Content>
</ContentPage>
and I wrote this in c# file :
namespace App1
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void OnButtonClicked(object sender, EventArgs e)
{
lblMessage.Text = "save";
}
}
}
The error i had it's in lblMessage variable in c# file it's :
The name 'lblMessage' does not exist in the current context
I do it from youtube channel and this is was exactly what he did, but it's worked with him and gives an error with me, any idea or help ?
1.Clean your project first
2.Rebuild it, change your XAML file properties (Build Action) from Embedded Resource to C# complier, Rebuild your project (will throw errors).
3.Switch back your XAML file properties to Embedded Resource, Rebuild.
Refer to this link: https://forums.xamarin.com/discussion/96447/the-name-initializecomponent-does-not-exist-in-the-current-context

WinUI 3 runtime localization

I am developing WinUI 3 app, currently stuck with localization. Although I wrote separate resw resource files for different cultures and localized with x:Uid I cannot find a way to change language in app runtime.
Setting Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride only works fine for settings startup language.
Is runtime localization in WinUI 3 even possible?
I've spent many hours on this subject. Here's my sincere advice: DO NOT TRY TO LOCALIZE YOUR VIEWS. Also, don't try to handle changes to the language at RunTime. No one does this, you'll never see an ROI in the investment.
Make all your localization in the view models and use the StringLocalizer class that's built into .NET's DI. Add the string localizer to the DI first:
this.serviceProvider = new ServiceCollection()
.AddLogging()
.AddLocalization();
Then, in your .NET or .Net Standard library, in your view model, add the following initialization:
private readonly IStringLocalizer<LandingViewModel> stringLocalizer;
public MyViewModel(IStringLocalizer<MyViewModel> stringLocalizer)
{
this.stringLocalizer = stringLocalizer;
}
Now, if you have some text you want to display, say on a button, you'd have:
public string SignUpText => this.stringLocalizer["SignUp"];
And in XAML, you'd have:
<Button Content="{x:Bind ViewModel.SignUpText}"/>
Finally, give the RESX file the same name as your view model. It should be an Embedded Resource with, and this is important, no custom tool:
Original Answer:
I think you're on the right track. If you are trying to change the language at runtime, call a method that will set Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride to the new language "string". But then after that, you will also have to reload your Page so that the new language takes effect.
private void ReloadLanguage(string languageOverride)
{
// Change the app language
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = languageOverride;
// Be sure to clear the Frame stack so that cached Pages are removed, otherwise they will have the old language.
Frame.BackStack.Clear();
// Reload the page that you want to have the new language
Frame.Navigate(typeof(MainPage));
}
-OR-
You'll have to call your ResourceLoader for the UI components you need/want to refresh one at a time.
private void RefreshUIText()
{
var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
this.myXAMLTextBlockElement.Text = resourceLoader.GetString("Farewell");
}
Updated Answer:
According to Microsoft online documentation, they suggest that anytime you change the language for you "to reload your strings from the default ResourceContext". I know this is not ideal, but it appears to work.
I got the following Example Solution below to work:
MainWindow.xaml
<Grid>
<Frame x:Name="MainFrame"/>
</Grid>
MainWindow.xaml.cs
public MainWindow()
{
this.InitializeComponent();
MainFrame.Navigate(typeof(MainPage));
}
MainPage.xaml
<Grid>
<StackPanel>
<TextBlock x:Uid="Greeting" x:Name="Greeting" Text="" Margin="15"/>
<TextBlock x:Uid="Farewell" x:Name="Farewell" Text="" Margin="15"/>
<Button x:Name="SelectLanguageButton" Click="SelectLanguageButton_Click" Content="Select Language" Margin="15"/>
</StackPanel>
</Grid>
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
RefreshUIText();
}
private void SelectLanguageButton_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(LanguagePage));
}
private void RefreshUIText()
{
var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForViewIndependentUse();
this.Greeting.Text = resourceLoader.GetString("Greeting/Text");
this.Farewell.Text = resourceLoader.GetString("Farewell/Text");
}
}
LanguagePage.xaml
<Grid>
<StackPanel>
<Button x:Name="EnglishButton" Click="EnglishButton_Click" Content="English" Margin="15"/>
<Button x:Name="FrenchButton" Click="FrenchButton_Click" Content="French" Margin="15"/>
</StackPanel>
</Grid>
LanguagePage.xaml.cs
public sealed partial class LanguagePage : Page
{
public LanguagePage()
{
this.InitializeComponent();
}
private void EnglishButton_Click(object sender, RoutedEventArgs e)
{
ReloadLanguage("en");
}
private void FrenchButton_Click(object sender, RoutedEventArgs e)
{
ReloadLanguage("fr");
}
private void ReloadLanguage(string languageOverride)
{
// Change the app language
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = languageOverride;
// Be sure to clear the Frame stack so that cached Pages are removed, otherwise they will have the old language.
Frame.BackStack.Clear();
// Reload the page that you want to have the new language
Frame.Navigate(typeof(MainPage));
}
}
Resource Files and contents, Solution Explorer
Also remember to add your language declarations in the Package.appxmanifest file
I created new project - Blank App, Packaged with WAP(WinUI 3 in Desktop) with latest project templates, which come with VS extension Windows APP SDK C# VS2019. As you noticed - I am using VS 2019, Community edition. I am attaching csproj configuration of a project below.
There is a frame in main window which navigates to main page. There is only one button on main page which leads to LanguagePage on click.
Goal is to change language, clear navigation stack and navigate back to main page. However, various scenarios in SetAppLanguage didn't produced wanted result.
Please take a look at https://www.py4u.net/discuss/731870 - tried all scenarios, no effect on GUI.
Nevertheless Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView(); is throwing a COMException: 'Resource Contexts may not be created on threads that do not have a CoreWindow. (0x80073B27)'
I have a NuGet package called WinUI3Localizer that helps you with localization.
GitHub:
https://github.com/AndrewKeepCoding/WinUI3Localizer
No app restart
You/users can edit localized strings even after deployment
You/users can add new languages even after deployment
Uses standard "Resources.resw"

Xamarin Cross-Platform App Solution Build failed?

I am absolutely new to Xamarin form. I think my question that i am going to ask will be not too good but the problem i faced is very strange and i don't know how to solved it.
Problem:
I created a brand new Cross-Platform project in visual studio 2017.
and a wrote some code and when i run my application the Build Solution is failed.
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:HelloWorld"
x:Class="HelloWorld.MainPage">
<StackLayout>
<!-- Place new controls here -->
<Label x:Name="_label" Text="Welcome to Xamarin.Forms!"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<Entry x:Name="EnterYourName" Placeholder="Write your name"/>
<Button Text="Say Hello !" Clicked="Button_Clicked" />
</StackLayout>
</ContentPage>
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Form;
namespace HelloWorld
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
void Button_Clicked(object sender, EventArgs e)
{
_label.Text = "Welcome" + " " + EnterYourName.Text;
}
}
}
Errors:
All The necessary using statements are included and when i click
on build solution it give me this error...
The Type or namespace name 'System' could not found (are you missing
a using directives or assemblies reference.)
The Type or namespace name 'Xamarin' could not found (are you missing
a using directives or assemblies reference.)
Predefined type 'System.Void' is not defined or imported. and so on.
How to solve this issue ? I shall be very thankful.
Thanks.
This project is fine, so the problem is not code related (unless you have something strange in App.Xaml and App.Xaml.cs).
You may need to:
clean the project
restore Nuget packages
If the problem appears only on the single platform you might need to check your connection with Mac or see if you have installed all required Android SDK/components.

Xamarin InitializeComponent() cannot be used when inherited from application

I followed the Xamarin Forms quickstart guide and my only error is:
Error CS0103 The name 'InitializeComponent' does not exist in the current context.
The app.xaml only seems to generate this error when the class "App" inherits from "Application", when I make it inherit from ContentPage, it works.
The build action of the app.xaml is "Embedded resource" and the custom tool is "MSBuild:UpdateDesignTimeXaml". I've tried to run the custom tool on the app.xaml, but it does not work. Also the package Xamarin.Forms is updated to the latest version and I have deleted and readded the app.xaml.
Does anyone have a solution for this?
I'm using vs2015 Update 3 and Portable class libraries.
EDIT:
App.xaml.cs
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace Phoneword
{
public partial class App : Application
{
public App()
{
this.InitializeComponent();
MainPage = new Phoneword.MainPage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
App.xaml
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="PhoneWord.App">
<Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</Application>
You don't give that much information, but my guess is there's a mismatch between base classes
the xaml should start with
<Application ....
x:Class="MyApp" >
indicating that MyApp inherits from Application.
the code behind should reflect this as well:
public class MyApp : Application
if both base types mismatches, you're in trouble.

The name 'InitializeComponent' does not exist in the current context when creating new xaml file

I have searched for an answer to this question for a while so I hope that my instance can be solved. I created a new Xamarin.Forms shared projects in visual studio 2015 community. I created a new xaml file and name it LoginPage and placed it in a folder named Pages in the shared app project. After adding the Xamarin.Forms namespace for it to recognize Page and removing this. before InitializeComponent I have this:
using Xamarin.Forms;
namespace BeneFit.Pages
{
public sealed partial class LoginPage : Page
{
public LoginPage()
{
InitializeComponent(); //This has the red squiggly
}
}
}
The Xaml file here has not been changed at all:
<Page
x:Class="BeneFit.Pages.LoginPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BeneFit.Pages"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>
</Page>
One thing I have notice a lot is that the build action needs to be Page which I made sure of in this case. Also the suggested quick fix was to add this:
private void InitializeComponent()
{
throw new NotImplementedException();
}
which doesnt really solve the issue because I know I should have to do it. Any help or suggestions would be huge, ive been trying to deal with this for a while.
When you create a new control or page in XAML, a hidden partial class file is also generated behind the scenes, this holds your InitializeComponent() method. In the case of a page called LoginPage the generated code behind will be called LoginPage.g.i.cs, and it should reside in the folder structures under the obj folder.
Your XAML line
xmlns:local="using:BeneFit.Pages"
does look a bit funky, I would change that to
xmlns:local="clr-namespace:BeneFit.Pages"
Go to each project folder (shared, .Android, .ios etc) and delete obj and bin folders (this will remove the hidden partial .g file)
Rebuild the solution.
Three checks to fulfill:
1 - Latest Xamarin Forms nuget installed same versions for all platforms
2 - For page.Xaml properties are :
Build Action: Embedded Resource
Copy to output dir: Do not copy
Custom tool (most common error when created page manually): MSBuild:UpdateDesignTimeXaml
For page.cs properties are:
Build action: Compile
Copy to output dir: Do not copy
3 - Right-click project - Unload project, then reload project.
That looks like UWP XAML not Xamarin Forms XAML.
Are you creating the wrong new thing?
You should be creating a new Xamarin.Forms Content Page

Categories

Resources