Xamarin InitializeComponent() cannot be used when inherited from application - c#

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.

Related

WPF app published as exe unhandled exception error

I have been trying to publish my WPF app as a standalone .exe instead of as a manifest. I've followed several posts from here and have added the following lines to the .csproj file:
<PropertyGroup>
<PublishSingleFile>true</PublishSingleFile>
</PropertyGroup>
But that didn't work. So as suggested by another user, I compiled my application as a console app in order to see any errors that are thrown. The console showed these errors:
The only reference to RED.APP is in my AppView.xml file here:
<Application x:Class="RED.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RED">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<local:Bootstrapper x:Key="Bootstrapper" />
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
I'm using a bootstrapper because I am using CaliburnMicro, here is the bootstrapper class:
using System.Windows;
using Caliburn.Micro;
using RED.ViewModels;
namespace RED
{
public class Bootstrapper : BootstrapperBase
{
public Bootstrapper() //Constructor
{
Initialize();
LogManager.GetLog = type => new DebugLog(type);
//Uses the output window in visual studio to display logging information it collects from Caliburn.Micro
}
//Override the startup method and launch the shell instead
protected override void OnStartup(object sender, StartupEventArgs e)
{
DisplayRootViewFor<ShellViewModel>();
}
}
}
Is the error caused by CaliburnMicro? I am not sure what exactly the error is saying. I have resolved a couple of warnings about some references that weren't resolved, and have boiled it down to this last error and am stuck. The event viewer was showing errors 1000 and 1026 when I tried to launch the .exe. I'm not seeing any debug text in the output from Caliburn.
Thanks in advance for the assistance.

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

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.

Community Toolkit MVVM - Placing WPF Window XAML files in a Views folder?

I have a question for people familiar with the Community Toolkit MVVM regarding best practices for building up the Views part of MVVM. I have started a new project to try to get things figured out before trying to implement this into my actual project. My main question is, if you have multiple views/windows for different purposes in a WPF application, is it not a good idea to place them into a View or Views folder? If so, I'm having a hard time getting the application to launch the main window.
System.IO.IOException: 'Cannot locate resource 'wpf_mvvm_test.views.mainwindow.xaml'.'
The first thing I tried was just moving the MainWindow.xaml file to the views folder, which caused the runtime error as soon as it compiled. I started changing the namespace references for the MainWindow.xaml, MainWindow.xaml.cs, App.xaml, App.xaml.cs, as well as the startup URI to reflect the namespace for the folder, WPF_MVVM_Test.Views, and none of the changes I have made have prevented the error. I did leave the App.xaml file in the main project, not in the folder. If I try to move it into the Views folder, even if I change its x:Class and the App.xaml.cs namespace to WPF_MVVM_Test, when I try to run it, it gives me an error that there is no static Main entrypoint.
Is there no way to place the WPF window files into a folder? If it's not possible, it's not possible, but if it is possible, I would love to figure out how, as it would make it easier to keep the solution organized.
MainWindow.xaml:
<Window x:Class="WPF_MVVM_Test.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPF_MVVM_Test.Views"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
MainWindow.xaml.cs:
using System.Windows;
using WPF_MVVM_Test.ViewModels;
using WPF_MVVM_Test.Views;
namespace WPF_MVVM_Test.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
}
App.xaml:
<Application x:Class="WPF_MVVM_Test.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF_MVVM_Test"
StartupUri="WPF_MVVM_Test.Views.MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
App.xaml.cs:
using System.Windows;
using WPF_MVVM_Test.Views;
namespace WPF_MVVM_Test
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
Thanks to ASh for the very helpful reply. I'm not sure what is preventing the application from compiling by moving the MainWindow.xaml file in to a folder, but the workaround references ASh provided definitely works.
First, I removed the StartupUri statement from the App.xaml file.
Second, in the App.xaml.cs file, I added an override for an OnStartup event as shown below, ensuring the folder that the MainWindow files are located in is in the using statements.
App.xaml.cs
using System.Windows;
using WPF_MVVM_Test.Views;
namespace WPF_MVVM_Test
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new MainWindow().Show();
}
}
}

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

Embedding and data-binding android spinner in xaml content page in xamarin-forms

I am trying to embed a native android spinner in a xamarin forms content page. I have had some joy embedding a check-box from the developer documentation but I want to add a spinner. From the documentation, I should be able to data-bind normally to any native control. So I data-bound an ObservableCollection of strings to a native spinner like so:
<?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:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
xmlns:android="clr-
namespace:Android.Widget;assembly=Mono.Android;targetPlatform=Android"
xmlns:androidForms="clr-namespace:Xamarin.Forms;
assembly=Xamarin.Forms.Platform.Android;targetPlatform=Android"
x:Class="CashFlowBuddie.Views.SelectPage"
Title="{Binding Title}">
<ContentView HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Label Text="Hi there from new app" FontSize="Large" FontAttributes="Bold" TextColor="Aquamarine"/>
<android:Spinner x:Arguments="{x:Static androidForms:Forms.Context}" ItemsSource="{Binding TextNames}" />
</ContentView>
</ContentPage>
This is my xaml page's viewmodel:
public class SelectPageViewModel : ViewModelBase
{
private ObservableCollection<string> _text;
public ObservableCollection<string> TextNames
{
get { return _text; }
set { SetProperty(ref _text, value); }
}
public SelectPageViewModel(INavigationService navigationService, IPageDialogService dialogService):base(navigationService,dialogService)
{
Title = "Select Option Page";
TextNames = new ObservableCollection<string>
{
"First",
"Second",
"Third"
};
}
}
From this you can tell that its a prism powered xamarin forms app. And I register my page for navigation properly:
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("NavigationPage/MainPage/SelectPage");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<MainPage>();
Container.RegisterTypeForNavigation<MainNavigation>("NavigationPage");
Container.RegisterTypeForNavigation<SelectPage>();
}
}
I made sure that I disabled XamlC from AssemblyInfo.cs since I cannot use XamlC when embedding native controls and views. My app crashes when I do the data-binding to the observablecollection of textnames. So I would like to know if someone has done this and had any joy? I looked at the spinner in the xamarin.android docs says a xml backed string array is created and is the source of data for the spinner. I did something similar using an observablecollection but if I run the app it just crashes. If I run the app without the data binding, it works and shows the app with the spinner but no data.
Can anyone shed any light on how to get this done? looked at docs and nothing so far though I am still digging?
Thanks
You may refer to Subclassing Native Views, seems like for control like Spinner is not suitable for instantiating in XAML. The ItemsSource property should be created in the subclass of native Spinner
To check the official demo, you may refer to Subclassed Native Views.

Categories

Resources