skip to Main Content

I have a C# code which I would like to run through a simple button click using WPF. I am not sure how to achieve this since the creation of a WPF solution in Visual Studio already comes with a .cs file.
If I delete the existing namespace, the program wouldn’t run, thus, is there any way I can add a second namespace and run it?

Thank you!

I have not tried anything in specific because of my lack of knowledge.

2

Answers


  1. New WPF projects generate automatically some files that are:
    1.App.xaml
    2.MainWindow.xaml

    ‘App.xaml’ is the first file to be processed when your project is run

    <Application x:Class="WpfApp2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp2"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         
    </Application.Resources>
    

    On line 5, open the file ‘MainWindow.xaml’. The program would not run if you deleted ‘MainWindow.xaml’ or ‘App.xaml’.

    Login or Signup to reply.
  2. Maybe you think things are too complicated. Regarding wpf, you only need to follow the steps below to use the Button trigger method:

    1. Right-click your project => Add => New Item, add a Class.

    enter image description here

    1. Write a method in the newly created Class:

    enter image description here

    using System.Windows;
    
    namespace buttonTest
    {
        public class Class1
        {
            public void Test()
            {
                MessageBox.Show("Test successfully");
            }
        }
    }
    
    1. Drag a button from the toolbox in MainWindows

    enter image description here

    1. Put the mouse on the button, double-click the button when the mouse shows an arrow, and write the previous method to Button_Click(object sender, RoutedEventArgs e)

       private void Button_Click(object sender, RoutedEventArgs e)
       {
           Class1 class1 = new Class1();
           class1.Test();
       }
      

    Start wpf, click the button to call the previous method

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search