简体   繁体   中英

Accessing C# WPF from F#

I know I can build a WPF application with FSharp.ViewModule or FSharp.Desktop.UI. In this case I'm trying to build the GUI part in C# and access it from F#. I can start the C# application from F#, and it shows the MainWindow however I cannot access any control on it from code. How would I refer to the Button (Name:button) on this form? MainWindow or App doesn't show it in my initial setup.

The C# View is just a MainWindow with a Button on it.
在此处输入图片说明

The F# code is this:

open System
open WpfView    

[<STAThread>]

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

    app.Run(win) |> ignore

The controls on your WPF are 'internal'. 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.

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.

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. That way you can use data binding to bind to models you have written in F#.

By default, the controls in a WPF form are declared as internal and are not visible outside the assembly of the form. You can change that in the XAML of the WPF form by specifying the x:FieldModifier attribute like this:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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