IronPython WPF withe RevitPythonShell

2019-05-16 12:15发布

问题:

I've written this script based on the snippets I found here on stackoverflow but get this error at runtime:

System.InvalidOperationException: Cannot create more than one System.Windows.Application instance in the same AppDomain.

I know it's got something to do with the fact that the last statement is creating a new Application instance within the same AppDomain but I don't know how to fix this. Here is the script:

clr.AddReference('PresentationCore')
clr.AddReference("PresentationFramework")
clr.AddReference('Microsoft.Dynamic')
clr.AddReference('Microsoft.Scripting')
clr.AddReference('System')
clr.AddReference('IronPython')
clr.AddReference('IronPython.Modules')
clr.AddReference('IronPython.Wpf')
from System.Windows import Application, Window
from IronPython.Modules import Wpf as wpf

class AboutWindow(Window):
    def __init__(selfAbout):
        wpf.LoadComponent( selfAbout, os.path.join( folder, 'AboutWindow.xaml' ))

class MyWindow(Window):
    def __init__(self):
        wpf.LoadComponent( self, os.path.join( folder, 'IronPythonWPF.xaml' ))

    def MenuItem_Click(self, sender, e):   
        form = AboutWindow()
        form.ShowDialog()

if __name__ == '__main__':
    Application().Run( MyWindow() )

This seems to be the solution but don't know what parts of this code I would need to fix mine.

Here is the contents for the two XAML files:

__WIP__wpfTest__AboutWindow.xaml

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="AboutWindow" Height="300" Width="300">
    <Grid>
        <TextBlock Text="AboutWindow" />
    </Grid>
</Window>

__WIP__wpfTest__IronPythonWPF.xaml

<Window 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       Title="IronPythonWPF" Height="300" Width="300">
    <StackPanel>
        <Menu>
            <MenuItem Header="About" Click="MenuItem_Click" />
        </Menu>
        <TextBlock Text="MainWindow" />
    </StackPanel>
</Window> 

回答1:

According to msdn, you should be able to use Window.Show (for a modeless version) or Window.ShowDialog (if you want to stay in the Revit API context)

The Application().Run( MyWindow() ) line basically sets up an event loop - something Revit already did for you at startup, so you can just go ahead and show your windows :)

I can't really test this solution since I don't have AboutWindow.xaml and IronPythonWPF.xaml, so I'm just guessing here... Have a go and tell me how it went.