我一直喜欢使用基于XAML的框架(如WPF、Xamarin.Forms等)进行GUI开发。在Python中,我使用了PyQT和tkinter,但我真的不喜欢使用它们。我最近发现了Python.NET(http://pythonnet.github.io/),我一直在尝试使用Python构建基于WPF/XAML的应用程序
我取得了一些成功,但也遇到了很多障碍。我现在试图克服的一个障碍与数据绑定有关,特别是使用我在XAML中定义的数据模板。我正在尝试填充一个列表框,并且为列表框的项目定义了一个数据模板。这是我的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中正常工作提供指导。谢谢
__namespace__
。例如相关问题 更多 >
编程相关推荐