我刚开始将 IronPython 与 WPF 一起使用,但我不明白应该如何完成绑定(bind)。
通常在 WPF 中我会做这样的事情:
<ListBox Name="MyListBox">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<DockPanel>
<TextBlock Text="{Binding Path=From}" />
<TextBlock Text="{Binding Path=Subject}" />
</DockPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
然后在我的代码后面:
MyListBox.ItemsSource = new ObservableCollection<Email>()
但是在 IronPython 中,我们不能有 ObservableCollection 对象,只有类型。这不起作用:
MyListBox.ItemsSource = new ObservableCollection[email]()
因为它抛出异常:“预期的数组 [类型],得到了 classobj”
我应该做些什么?请帮忙!
最佳答案
我自己解决了这个问题,我有一些错误,也错过了一些关键点。我希望这个答案可以帮助别人。
首先是您需要 IronPython 目录中的 tutorial/目录中的 pyevent.py。
其次,我们需要一个辅助类:
class NotifyPropertyChangedBase(INotifyPropertyChanged):
"""INotifyProperty Helper"""
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 Email(NotifyPropertyChangedBase):
"""
use setter getter.
IronPython 2.6 or later.
"""
@property
def From(self):
return self._From
@From.setter
def From(self, value):
self._From = value
self.OnPropertyChanged("From")
@property
def Subject(self):
return self._Subject
@Subject.setter
def Subject(self, value):
self._Subject = value
self.OnPropertyChanged("Subject")
最后设置ListBox的ItemSource:
self.data = ObservableCollection[Email]()
self.MyListBox.ItemsSource = self.data
归功于此链接的帮助:http://palepoli.skr.jp/wp/2009/06/28/wpf-listview-databinding-for-ironpython/
关于wpf - 如何绑定(bind)到 IronPython 中的 ListBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6234476/