<p>在IronPython 2.7中,wpf.LoadComponent方法将连接与XAML UI元素同名的任何属性。如果您使用的是IronPython 2.6,那么您需要使用WombatPM建议的代码。因此,对于IronPython 2.7,如果使用以下XAML:</p>
<pre><code><Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="IronPyWpf" Height="300" Width="300">
<Grid>
<Button x:Name="button" Content="Button" Height="23" HorizontalAlignment="Left" Margin="103,226,0,0" VerticalAlignment="Top" Width="75" />
<TextBox x:Name="textbox" Height="182" HorizontalAlignment="Left" Margin="24,21,0,0" VerticalAlignment="Top" Width="237" />
</Grid>
</Window>
</code></pre>
<p>然后,可以定义两个名为button和textbox的属性来访问UI元素:</p>
<pre><code>class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'IronPyWpf.xaml')
self._button.Content = 'My Button'
self._textbox.Text = 'My Text'
def get_button(self):
return self._button
def set_button(self, value):
self._button = value
button = property(get_button, set_button)
def get_textbox(self):
return self._textbox
def set_textbox(self, value):
self._textbox = value
textbox = property(get_textbox, set_textbox)
</code></pre>
<p>实际上,通过删除属性定义,您似乎可以进一步简化代码:</p>
<pre><code>class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'IronPyWpf.xaml')
self.button.Content = 'My Button'
self.textbox.Text = 'My Text'
</code></pre>
<p>不幸的是,正如您已经看到的,当您试图编辑XAML并为UI元素命名时,Visual Studio似乎会崩溃,出现空引用异常。</p>