我的最终目标是将以下代码从C#转换为IronPython(来源:https://wpf-tutorial.com/data-binding/responding-to-changes/):
using System;
using System.Collections.Generic;
using System.Windows;
namespace WpfTutorialSamples.DataBinding
{
public partial class ChangeNotificationSample : Window
{
private List<User> users = new List<User>();
public ChangeNotificationSample()
{
InitializeComponent();
users.Add(new User() { Name = "John Doe" });
users.Add(new User() { Name = "Jane Doe" });
lbUsers.ItemsSource = users;
}
private void btnAddUser_Click(object sender, RoutedEventArgs e)
{
users.Add(new User() { Name = "New user" });
}
private void btnChangeUser_Click(object sender, RoutedEventArgs e)
{
if(lbUsers.SelectedItem != null)
(lbUsers.SelectedItem as User).Name = "Random Name";
}
private void btnDeleteUser_Click(object sender, RoutedEventArgs e)
{
if(lbUsers.SelectedItem != null)
users.Remove(lbUsers.SelectedItem as User);
}
}
public class User
{
public string Name { get; set; }
}
}
相关的XAML:
<ListBox Name="lbUsers" DisplayMemberPath="Name"></ListBox>
到目前为止,这是我使用http://palepoli.skr.jp/wp/2009/06/28/wpf-listview-databinding-for-ironpython/中的信息得出的结论:
import wpf
from System import *
from System.Collections.Generic import *
from System.Windows import *
from System.Windows.Controls import *
from System.Windows.Data import *
from System.ComponentModel import *
from System.Collections.ObjectModel import *
from System.Windows import Application, Window
class NotifyPropertyChangedBase(INotifyPropertyChanged):
PropertyChanged = None
def __init__(self):
(self.PropertyChanged, self._propertyChangedCaller) = make_event()
def add_PropertyChanged(self, value):
self.PropertyChanged += value
def remove_PropertyChanged(self, value):
self.PropertyChanged -= value
def OnPropertyChanged(self, propertyName):
self._propertyChangedCaller(self, PropertyChangedEventArgs(propertyName))
class User(NotifyPropertyChangedBase):
@property
def Name(self):
return self._Name
@Name.setter
def Name(self, value):
self._Name = value
self.OnPropertyChanged("Name")
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'WpfApplication1.xaml')
self.users = ObservableCollection[User]()
temp = User()
temp.Name = "Test"
self.users.Add(temp)
lbUsers.ItemsSource = users
if __name__ == '__main__':
Application().Run(MyWindow())
但是,此代码在创建“ self.users”对象时崩溃。我发现,如果我初始化使用STR的ObservableCollection做出添加功能的XAML中的DisplayMemberPath和输入适当的修改,代码运行良好,但我感兴趣的是使用自定义类。从我在网上看到的各种物品,似乎没有要使用ItemsSources和中的ObservableCollection IronPython的共识,所以我希望有人能够帮助我澄清在我的问题。