python.net构建了带有自定义控件的WPF窗口



我正在尝试使用python.net和WPF来获得现代外观&在我的应用程序上感受
我还想使用FluentWPF库来赋予它MS Fluent风格。

我构建了FluentWPF项目,并在python.net中加载了dll,并构建了一个简单的窗口XAML来加载:

import os
import clr
# add WPF ref, load FluentWPF dll
clr.AddReference("wpfPresentationFramework")
dll = os.path.join(os.getcwd(), r"FluentWPF-masterFluentWPFbinDebugnet45FluentWPF.dll")
clr.AddReference(dll)
from SourceChord.FluentWPF import *
from System import Exception
from System.IO import *
from System.Windows.Markup import XamlReader, ParserContext
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("window.xaml")
ctx = ParserContext()
ctx.XmlnsDictionary.Add("fw", "clr-namespace:SourceChord.FluentWPF;assembly=FluentWPF")
self.window = XamlReader.Load(stream.BaseStream, ctx)
Application().Run(self.window)
except Exception as e:
print(e.Message)
# start app
thread = Thread(ThreadStart(MyWindow))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()

窗口XAML:

<fw:Window x:Class="Window"
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:fw="clr-namespace:SourceChord.FluentWPF;assembly=FluentWPF"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="AcrylicWindow"
Width="300"
Height="300"
mc:Ignorable="d">
<Grid Background="#70FFFFFF">
<TextBlock Margin="10"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="This is AcrylicWindow"
TextWrapping="Wrap" />
</Grid>
</fw:Window>

到目前为止,这就是我所拥有的,但当我运行此代码时,我会收到错误:

'Cannot create unknown type '{clr-namespace:SourceChord.FluentWPF;assembly=FluentWPF}Window'.' Line number '1' and line position '2'.

我试图通过将这些对齐添加到Window ctor来修复它,认为它可以替换库示例中使用的缺失的App.xaml:

ctx = ParserContext()
ctx.XmlnsDictionary.Add("fw", "clr-namespace:SourceChord.FluentWPF;assembly=FluentWPF")

在App.xml中还有这样一行:

<ResourceDictionary Source="pack://application:,,,/FluentWPF;component/Styles/Controls.xaml" />

这是我也可以通过ParserContext注入的东西吗?或者我错过了什么?我对WPF还不是很熟悉。

clr.AddReference("TestWpfProjectForPython")

from TestWpfProjectForPython import MainWindow

def app_thread():
sb = MainWindow()
sb.ShowDialog()
from System.Threading import ApartmentState, Thread, ThreadStart
thread = Thread(ThreadStart(app_thread))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()

将WPF窗口作为对话框打开是很重要的,因为否则启动线程将立即结束。

最新更新