我一直喜欢使用基于 XAML 的框架(例如 WPF、Xamarin.Forms 等)进行 GUI 开发。在 Python 中,我使用过 PyQT 和 tkinter,但我真的不喜欢使用它们中的任何一个。我最近发现了 Python.NET ( http://pythonnet.github.io/ ),并且一直在尝试使用 Python 构建基于 WPF/XAML 的应用程序。
我取得了一些成功,但也遇到了很多障碍。我现在正在尝试克服的一个障碍与数据绑定(bind)有关,特别是使用我在 XAML 中定义的 DataTemplate。我正在尝试填充列表框,并且我已经为列表框的项目定义了一个数据模板。这是我的 XAML:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="RePlay Database Builder: Select a database"
Height="600"
Width="800">
<Grid>
<ListBox Margin="20,10" Name="MyListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Name: " FontWeight="Bold" HorizontalAlignment="Left" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=MyName}" HorizontalAlignment="Left" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Path: " FontWeight="Bold" HorizontalAlignment="Left" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=MyPath" HorizontalAlignment="Left" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
现在,我想填充该列表框并使所有内容正确“链接”。这是我尝试使用的当前代码,但它(显然)不起作用:
import clr
clr.AddReference("wpf\PresentationFramework")
clr.AddReference("System.Collections")
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 *
from System.Collections.Generic import List
import System
class TestObject(System.Object):
def __init__(self, my_name, my_path):
self.MyName = my_name
self.MyPath = my_path
class MyWindow(Window):
def __init__(self):
try:
stream = StreamReader('MyWindow.xaml')
self.window = XamlReader.Load(stream.BaseStream)
self.test_list = List[TestObject]()
self.test_list.Add(TestObject("Item1", "Path1"))
self.test_list.Add(TestObject("Item2", "Path2"))
self.test_list.Add(TestObject("Item3", "Path3"))
MyListBox = LogicalTreeHelper.FindLogicalNode(self.window, "MyListBox")
MyListBox.ItemsSource = self.test_list
Application().Run(self.window)
except Exception as ex:
print(ex)
if __name__ == '__main__':
thread = Thread(ThreadStart(MyWindow))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()
我想知道是否有人可以提供有关如何使 DataTemplates 在 Python.NET 中良好运行的指导。谢谢!
最佳答案
- 要创建一个 Python 类,从 .NET 的角度来看,它的行为类似于 .NET 类,您需要
__namespace__
。例如
class TestObject(System.Object):
__namespace__ = "MyApp.ViewModel"
def __init__(self, my_name, my_path):
super().__init__()
self.MyName = my_name
self.MyPath = my_path
- 如果这不起作用,您可能想尝试 https://github.com/Alex141/CalcBinding
关于Python .NET - 使用 XAML/WPF 进行 GUI 开发以及使用 DataTemplate 进行数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69633092/