從以下SO後使用公認的答案:How do I bind to a ListBox in IronPython?我設法填充和綁定米IronPython的代碼組合框和列表。
我會在這裏把所有的代碼的情況下,任何人找到他/她自己在同樣的情況:
首先是指定綁定需要在XAML變化爲ListBox的:
<DataTemplate x:Key="DataTemplate1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=lproperty, FallbackValue=Property}" />
<TextBlock Text="{Binding Path=lvalue, FallbackValue=Value}" Grid.Column="1" HorizontalAlignment="Right" Margin="0,0,-60,0" Width="360" />
</Grid>
</DataTemplate>
,那麼你還需要綁定列表框的內容給該模板:
<ListBox
x:Name="listBox1"
Grid.Column="0"
Grid.Row="0"
VerticalAlignment="Top"
Margin="0,30.223,14.5,0"
Height="368.639" HorizontalAlignment="Right" Width="442.619"
ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate1}"/>
我會把也是在這裏,填充組合框和列表框的整個代碼ssince是第n那麼大:
import wpf
from System.Windows import Application
from Window1 import Window1
from System.Windows.Controls import(ComboBox,
ComboBoxItem, ListBox, ListBoxItem)
from System.Collections.ObjectModel import *
from System.ComponentModel import *
from System.Windows.Controls import *
import pyevent
entries = {
1 : ('Email', '[email protected]'),
2 : ('Address', 'new york'),
3 : ('Notes', 'this is a dummy form'),
4 : ('Mobile Phone', '57234985734'),
5 : ('Work Fax', '5432578943'),
6 : ('Work Phone', '32465765765')
}
politetitles = {
1 : ('Mr'),
2 : ('Ms'),
3 : ('Mrs'),
4 : ('Sir'),
}
class NotifyPropertyChangedBase(INotifyPropertyChanged):
"""INotifyProperty Helper"""
PropertyChanged = None
def __init__(self):
(self.PropertyChanged, self._propertyChangedCaller) = pyevent.make_event()
def add_PropertyChanged(self, value):
if self.PropertyChanged is not None:
self.PropertyChanged += value
def remove_PropertyChanged(self, value):
if self.PropertyChanged is not None:
self.PropertyChanged -= value
def OnPropertyChanged(self, propertyName):
if self.PropertyChanged is not None:
self._propertyChangedCaller(self, PropertyChangedEventArgs(propertyName))
class myListEntry(NotifyPropertyChangedBase):
@property
def lvalue(self):
return self._lvalue
@lvalue.setter
def lvalue(self, value):
self._lvalue = value
self.OnPropertyChanged("lvalue")
@property
def lproperty(self):
return self._lproperty
@lproperty.setter
def lproperty(self, value):
self._lproperty = value
self.OnPropertyChanged("lproperty")
window = Window1()
#print window
app = Application()
combo = ComboBox()
titleitems = politetitles.items()
for key, data in titleitems:
item = ComboBoxItem()
item.Content = data
item.FontSize = 8
combo.Items.Add(item)
window.comboBox1.ItemsSource = combo.Items
listitems = entries.items()
listb = ObservableCollection[myListEntry]()
for key, data in listitems:
item = ListBoxItem()
lineitem = myListEntry()
lineitem.lproperty=data[0]
lineitem.lvalue=data[1]
listb.Add(lineitem)
window.listBox1.ItemsSource = listb
print listb
app.Run(window)