问题描述
我刚开始使用的IronPython与WPF,我不安静知道如何结合是应该做的。
I am just starting out using IronPython with WPF and I don't quiet understand how binding is supposed to be done.
通常,在WPF我只想做这样的事情:
Normally in WPF I would just do something like this:
<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>
然后在我的code背后:
Then in my code behind:
MyListBox.ItemsSource = new ObservableCollection<Email>()
但在IronPython的,我们不能有对象,只种一个ObservableCollection。这不工作:
But in IronPython we cannot have an ObservableCollection of objects, only types. This does not work:
MyListBox.ItemsSource = new ObservableCollection[email]()
由于它抛出异常:预期的数组[类型],得到了classobj
As it throws the Exception: "expected Array[Type], got classobj"
那我该怎么办?请帮助!
What am I supposed to do? Help please!
推荐答案
我的工作这一点我自己,我有一些事情错了,是缺少几个关键点为好。我希望这个回答能帮助别人。
I worked this out myself, I had a few things wrong and was missing a few key point as well. I hope this answer can help someone else.
首先是,你需要从教程/目录pyevent.py在IronPython的目录。
First was that you need pyevent.py from the tutorial/ directory in your IronPython directory.
其次,我们需要一个辅助类:
Second we need a helper class:
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))
然后,你需要声明的数据类,像这样:
Then you need to declare your data class like so:
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:
Finally set the ListBox's ItemSource:
self.data = ObservableCollection[Email]()
self.MyListBox.ItemsSource = self.data
感谢这个环节的帮助:的
这篇关于我如何绑定到IronPython的一个ListBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!