use python alongside c# in windows uwp app

  • Last Update :
  • Techknowledgy :

06/07/2022

Here's the code to copy and paste:

private async void Button_Click(object sender, RoutedEventArgs e) {
   MediaElement mediaElement = new MediaElement();
   var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
   Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello, World!");
   mediaElement.SetSource(stream, stream.ContentType);
   mediaElement.Play();
}

Here's the code to copy and paste:

private async void Button_Click(object sender, RoutedEventArgs e) {
   MediaElement mediaElement = new MediaElement();
   var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
   Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello, World!");
   mediaElement.SetSource(stream, stream.ContentType);
   mediaElement.Play();
}

Suggestion : 2

Although the Blank App (Universal Window) is a minimal template, it still contains a lot of files. These files are essential to all UWP apps using C#. Every project that you create in Visual Studio contains the files.,From the center pane, select the Blank App (Universal Windows) template.,In the left pane, you can see the tree view, now select Universal template from Templates → Visual C# → Windows.,The target version/minimum version dialog appears. The default settings are fine for this tutorial, so select OK to create the project.

  • Here, we have a single project which can target all Windows 10 Devices, and you will notice that both .NET Core and UWP are simplification of multi-targeting.

  • When a new project opens, its files are displayed on the right hand side of the Solution Explorer pane. You may need to choose the Solution Explorer tab instead of the Properties tab to see your files.

  • Although the Blank App (Universal Window) is a minimal template, it still contains a lot of files. These files are essential to all UWP apps using C#. Every project that you create in Visual Studio contains the files.

  • To see the running example, let us open MainPage.XAML and add the following code.

<Page 
   x:Class = "UWPFirstApp.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPFirstApp" 
   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}"> 
      <StackPanel HorizontalAlignment = "Center"> 
         <TextBlock Text = "Hello, world!"  
            Margin = "20" 
            Width = "200" 
            HorizontalAlignment = "Left"/> 
         <TextBlock Text = "Write your name." 
            Margin = "20" 
            Width = "200" 
            HorizontalAlignment = "Left"/> 
         <TextBox x:Name = "txtbox"  
            Width = "280" 
            Margin = "20" 
            HorizontalAlignment = "Left"/> 
         <Button x:Name = "button" Content = "Click Me" 
            Margin = "20" 
            Click = "button_Click"/> 
         <TextBlock x:Name = "txtblock"  
            HorizontalAlignment = "Left" 
            Margin = "20"/> 
      </StackPanel> 
   </Grid> 

</Page> 

Below is the click event of button in C#.

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Runtime.InteropServices.WindowsRuntime; 

using Windows.Foundation; 
using Windows.Foundation.Collections; 

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation;  

// The Blank Page item template is documented at 
// http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace UWPHellowWorld { 
   /// <summary> 
   /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
   public sealed partial class MainPage : Page { 
      public MainPage() { 
         this.InitializeComponent(); 
      }  
      private void button_Click(object sender, RoutedEventArgs e) { 
         if (txtbox.Text != "") 
            txtblock.Text = "Hello: " + txtbox.Text; 
         else 
            txtblock.Text = "You have not write your name"; 
      } 
   } 
} 

Suggestion : 3

To reference the binaries in the app, import the clr library and then use the addReference methods:

import wpf
import clr
clr.AddReference('Telerik.Windows.Controls.dll')
clr.AddReference('Telerik.Windows.Controls.Input.dll')
clr.AddReference('Telerik.Windows.Data.dll')
clr.AddReference('Telerik.Windows.Controls.GridView.dll')

As a last step, let’s write some XAML to show a DataGrid populated with ‘very sensitive business information’:

<Window        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"        Title="WpfApplication1" Height="240" Width="600" x:Name="Root">
       <Grid>
              
      <telerik:RadGridView telerik:StyleManager.Theme="Fluent"                              ItemsSource="ABCDE" />
          
   </Grid>
</Window>

Most of the real-world business apps in WPF use the MVVM pattern to separate the business logic from the View. But how to build the foundation of the MVVM inside our Python WPF project? Let me guide you through.

1. Build a base viewmodel class for all future view models. It should be property-changed ready in order to notify the UI for changes in the data:

from System.ComponentModel
import INotifyPropertyChanged, PropertyChangedEventArgs

class ViewModelBase(INotifyPropertyChanged):
   def __init__(self):
   self.propertyChangedHandlers = []

def RaisePropertyChanged(self, propertyName):
   args = PropertyChangedEventArgs(propertyName)
for handler in self.propertyChangedHandlers:
   handler(self, args)

def add_PropertyChanged(self, handler):
   self.propertyChangedHandlers.append(handler)

def remove_PropertyChanged(self, handler):
   self.propertyChangedHandlers.remove(handler)

    3.1. Define a ViewModel class for the data in each DataGrid row:

class Club(ViewModelBase):
   def __init__(self, name, est, capacity, stadName):
   ViewModelBase.__init__(self)
self.Name = name
self.Established = est
self.StadiumCapacity = capacity
self.StadiumName = stadName

   
    3.2. Define a main ViewModel which provides list of child models and defines commands to manipulate the data:  

from System.Collections.ObjectModel
import ObservableCollection
from datetime
import date

class ViewModel(ViewModelBase):
   def __init__(self):
   ViewModelBase.__init__(self)
self.Clubs = ObservableCollection[Club]()
self.Clubs.Add(Club('FC Barcelona', date(1899, 11, 29), 99354.0, 'Camp Nou'))
self.Clubs.Add(Club('Juventus F.C.', date(1897, 1, 1), 41507.0, 'Juventus Stadium'))
self.Clubs.Add(Club('Real Madrid', date(1902, 3, 6), 81044.0, 'Santiago Bernabeu'))
self.Clubs.Add(Club('Liverpool', date(1892, 1, 1), 54074.0, 'Anfield'))
self.Clubs.Add(Club('Manchester United', date(1878, 1, 1), 76212.0, 'Old Trafford'))
self.Clubs.Add(Club('Chelsea', date(1905, 1, 1), 42055.0, 'Stamford Bridge'))
self.ClearCommand = Command(self.clear)
self.DecreaseCapacityCommand = Command(self.decreaseCapacity)

def clear(self):
   self.Clubs.Clear()

def decreaseCapacity(self):
   for club in self.Clubs:
   cap = club.StadiumCapacity
club.StadiumCapacity *= 0.9
club.RaisePropertyChanged("StadiumCapacity")

Suggestion : 4

When learning C# at W3Schools.com, you can use our "Try it Yourself" tool, which shows both the code and the result. This will make it easier for you to understand every part as we move forward:,Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code.,Once the Visual Studio Installer is downloaded and installed, choose the .NET workload and click on the Modify/Install button:,Applications written in C# use the .NET Framework, so it makes sense to use Visual Studio, as the program, the framework, and the language, are all created by Microsoft.

Program.cs

using System;

namespace HelloWorld {
   class Program {
      static void Main(string[] args) {
         Console.WriteLine("Hello World!");
      }
   }
}

Program.cs

using System;

namespace HelloWorld {
   class Program {
      static void Main(string[] args) {
         Console.WriteLine("Hello World!");
      }
   }
}