将WindowsFormsHost控件添加到MainWindow会导致exe崩溃

时间:2016-05-23 03:29:24

标签: wpf xaml f#

我通过FsXaml在F#中使用WPF。 MainWindow工作,直到我添加一个WindowsFormsHost控件,此时它将在执行时崩溃并出现以下错误:

Unhandled Exception: System.Xaml.XamlObjectWriterException: Cannot create unknown type '{http://schemas.microsoft.com/winfx/2006/xaml/presentation}WindowsFormsHost'.
   at System.Xaml.XamlObjectWriter.WriteStartObject(XamlType xamlType)
   at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
   at FsXaml.InjectXaml.from$cont@37(String file, Object root, Stream resStream, Unit unitVar)
   at FsXaml.InjectXaml.from(String file, Object root)
   at Program.Win.InitializeComponent()
   at Program.Win..ctor()

我需要添加xaml或app来识别winformshost吗? C#生成的xaml在C#应用程序中运行。如果里面没有winformshost,F#app就可以运行。 C#和F#xamls之间的区别是x-local命名空间引用。

MainWindow.xaml:

<Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Height="124" VerticalAlignment="Top" Width="217"/>
        <WindowsFormsHost HorizontalAlignment="Left" Height="123" Margin="49,171,0,0" VerticalAlignment="Top" Width="394"/>

    </Grid>
</Window>

App.xaml

<Application 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

    </Application.Resources>
 </Application>

Program.fs:

open System
open System.Windows
open FsXaml
open Microsoft.FSharp.Control
open System.Windows.Forms
open System.Windows.Forms.Integration
open FSharp.Charting
open FSharp.Charting.ChartTypes

type App = XAML<"App.xaml">
type Win = XAML<"MainWindow.xaml">

[<STAThread>]
[<EntryPoint>]            
let main _ = 
    let app = App()
    let win = Win() 
    win.button.Content <- "Click!"  
    win.button.MouseRightButtonDown.Add (fun _ -> MessageBox.Show("OK") |> ignore) 
    app.Run win |> ignore
    0 

1 个答案:

答案 0 :(得分:3)

尝试显式添加命名空间(使用clr-namespace),就像使用winforms控件本身一样 - 只需使用System.Windows.Forms.Integration。我假设它不包含在默认的XAML命名空间中:)

xmlns:wfi="clr-namespace:System.Windows.Forms;assembly=WindowsFormsIntegration"