WPF GUI using XamlReader

From IronPython Cookbook

WPF GUI using XamlReader

In this example, we specify the layout using XAML (which is just an XML dialect). Then we convert the XAML string to a WPF Window object using the XamlReader class.

This example can run in Python.NET as well.

WPF Application

import sys
if 'win' in sys.platform:
    import pythoncom
    pythoncom.CoInitialize()
    
import clr
clr.AddReference("System.Xml")
clr.AddReference("PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
clr.AddReference("PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
from System.IO import StringReader
from System.Xml import XmlReader
from System.Windows.Markup import XamlReader, XamlWriter
from System.Windows import Window, Application

xaml = """
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="XamlReader Example" Width="300" Height="200">
    <StackPanel Margin="5">
        <Button Margin="5">One</Button>
        <Button Margin="5">Two</Button>
        <Button Margin="5">Three</Button>
    </StackPanel>
</Window>
"""
xr = XmlReader.Create(StringReader(xaml))
win = XamlReader.Load(xr)

Application().Run(win)


Back to Contents.

TOOLBOX
LANGUAGES