简体   繁体   English

从F#访问C#WPF

[英]Accessing C# WPF from F#

I know I can build a WPF application with FSharp.ViewModule or FSharp.Desktop.UI. 我知道我可以使用FSharp.ViewModule或FSharp.Desktop.UI构建WPF应用程序。 In this case I'm trying to build the GUI part in C# and access it from F#. 在这种情况下,我试图在C#中构建GUI部件并从F#中访问它。 I can start the C# application from F#, and it shows the MainWindow however I cannot access any control on it from code. 我可以从F#启动C#应用程序,它显示MainWindow,但是我无法从代码访问它的任何控件。 How would I refer to the Button (Name:button) on this form? 我将如何引用此表单上的按钮(名称:按钮)? MainWindow or App doesn't show it in my initial setup. MainWindow或App在我的初始设置中未显示。

The C# View is just a MainWindow with a Button on it. C#视图只是一个带有按钮的MainWindow。
在此处输入图片说明

The F# code is this: F#代码是这样的:

open System
open WpfView    

[<STAThread>]

do
    let app = App()
    let win = MainWindow()

    app.Run(win) |> ignore

The controls on your WPF are 'internal'. WPF上的控件是“内部”的。 That is they are only visible to code in the same assembly. 也就是说,它们仅对同一程序集中的代码可见。

see: Internal access modifier 请参阅:内部访问修饰符

Your F# and C# code are in separate assemblies so your F# code cannot access the internal members of classes in your C# code. 您的F#和C#代码位于单独的程序集中,因此您的F#代码无法访问C#代码中类的内部成员。

The controls are automatically generated by the xaml compiler so you can't change them directly however a simple fix would be to create public access methods and/or properties in your C# class that access the internal properties. 控件是由xaml编译器自动生成的,因此您不能直接更改它们,但是一个简单的解决方法是在访问内部属性的C#类中创建公共访问方法和/或属性。

Additionally, while you may have reasons to structure your code the way you have, it might be better to have the main entry point to the application in the C# assembly along with the WPF code and have that reference your logic in the F# assembly. 此外,虽然您可能有理由按自己的方式来构造代码,但最好将C#程序集中的应用程序的主入口点与WPF代码一起使用,并在F#程序集中引用您的逻辑。 That way you can use data binding to bind to models you have written in F#. 这样,您可以使用数据绑定来绑定到用F#编写的模型。

By default, the controls in a WPF form are declared as internal and are not visible outside the assembly of the form. 默认情况下,WPF窗体中的控件被声明为内部控件,并且在窗体的程序集外部不可见。 You can change that in the XAML of the WPF form by specifying the x:FieldModifier attribute like this: 您可以通过指定x:FieldModifier属性在WPF表单的XAML中进行更改,如下所示:

<Button x:Name="button" Content="Button" x:FieldModifier="public" />

However, it would be a better design to give the form your own properties to access the data in the form and not directly deal with the controls from outside. 但是,将表单赋予您自己的属性以访问表单中的数据,而不直接从外部处理控件将是更好的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM