pythonnet icon indicating copy to clipboard operation
pythonnet copied to clipboard

Event handling with WPF application

Open ChristianBauerEng opened this issue 6 years ago • 3 comments

Environment

  • Pythonnet version: 2.3.0
  • Python version: 3.6 (x64)
  • Operating System: Windows 10
  • IDE: Visual Studio 2017

Details

  • I would like to build a WPF application using python 3.6. My starting point is the DynamicGrid.py demo, and so far this works fine.

  • Now I would like to handle the control events in my python code. For this I replaced one of the labels in the DynamicGrid.xaml file with a button and added a Click event handler:

<Button Name="BTN" Content="Left" Grid.Column="0" Background="LightBlue" Click="btn_click"/>

The name of this event handler is also added to the corresponding python file DynamicGrid.py:

class MyWindow(Window):
    def __init__(self):
        stream = StreamReader("DynamicGrid.xaml")
        window = XamlReader.Load(stream.BaseStream)
        Application().Run(window)
     
    def btn_click(self, sender, e):
        print("Button clicked!")

Code like this is created when using the IronPython WPF Project in Visual Studio 2017 and works well with IPython. However, when incorporating event handlers like this with pythonnet I get the following Python.Runtime.PythonException:

XamlParseException : Line 16 ... "Error Creating "Click" from Text "btn_click".

It is however possible to add an event handler at runtime.

  • For this to work the Click-Event handler has to be removed from the XAML definition: <Button Name="BTN" Content="Left" Grid.Column="0" Background="LightBlue"/>

  • In the init code, search for the button's name and add the event handler:

        BTN = window.FindName('BTN')
        BTN.Click += self.btn_click

While this works it seems somewhat tedious to do this for larger, complex controls and UIs. Is there a way to declare the event handlers in the XAML file, just like in IronPython? If so, it might be helpful to others to include such a declaration in the DynamicGrid Demo.

ChristianBauerEng avatar Sep 03 '18 16:09 ChristianBauerEng

you cannot import wpf in python using pythonnet package. But you can load the XAML file using PresentationFramework in presentationframework have some limitation. The XamlReader can't perform event handling so we can manually add the event for that button in the python file, not in XAML file.

hear the gui.xaml code

<Window 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       Title="WpfApplication1" Height="300" Width="300">
    <Grid>
        <Label Content="Hello world" HorizontalAlignment="Left" Height="32" Margin="65,77,0,0" VerticalAlignment="Top" Width="119"/>
        <Button Name="button1" Content="Button" HorizontalAlignment="Left" Margin="65,145,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window> 

Then hear python code

import clr
clr.AddReference("wpf\PresentationFramework") 
from System.IO import *
from System.Windows.Markup import XamlReader
from System.Windows import *
from System.Threading import Thread, ThreadStart, ApartmentState
from System.Windows.Controls import *

class MyWindow(Window):
    def __init__(self):
        try:
            stream = StreamReader('gui.xaml')
            self.window = XamlReader.Load(stream.BaseStream)
            ButtoninXAML = LogicalTreeHelper.FindLogicalNode(self.window, "button1") 
            ButtoninXAML.Click +=  RoutedEventHandler(self.Button_Click)
            Application().Run(self.window)      
        except Exception as ex:
            print(ex)
    def Button_Click(self, sender, e):
        print('clicked')


if __name__ == '__main__':
    thread = Thread(ThreadStart(MyWindow))
    thread.SetApartmentState(ApartmentState.STA)
    thread.Start()
    thread.Join()

Try this also working

bmrselvan avatar Aug 31 '19 17:08 bmrselvan

but how about code completion for .net in pycharm here? Because of pycharm is writing "Unresolved reference" but application work fine. Should i write firstly in c# in Visual Studio, prepare there the code and copy him and adapt to python?

image

nikitatrast avatar Oct 30 '19 22:10 nikitatrast

I remember that you can try to get intellisense code from IronPython, and rewrite your code back to PythonNET

PlashSpeed-Aiman avatar May 28 '22 11:05 PlashSpeed-Aiman