简体   繁体   中英

F# WPF set a member value of an object after the constructor

I was having this problem earlier, where when I would try to set the height of a WPF window, it would give me this error:

unexpected identifier in member definition

I found a workaround by setting all the members's values in the constructor.

My old code looked like this:

module UI=

    type Display () = 

       let window = new Window()
       window.Height <- 600

I got it to to work by doing this:

module UI=

    type Display () = 

    let window = new Window(Height = 600.00, Width = 800.00)

But I can't help but wondering if there is some way to set the height (or other members) AFTER calling the window constructor?

I say this because the . operator is incredibly useful to me, since I am still learning the .NET framework, I don't know all of the members of a particular class. I would rather use the . operator to browse its members and see if I missed anything than have to go to the MSDN online. Also, its harder to read if I have a lot of member values set in the constructor.

Do I need to declare the window as mutable?

Actually, after some careful research. I have found I needed a do binding.

as stated clearly on the MSDN here

A do binding appears together with or after let bindings but before member definitions in a class definition. Although the do keyword is optional for do bindings at the module level, it is not optional for do bindings in a class definition.

Even though they do not appear to be required for the class that has your main method, they are required for other classes.

module UI=

    type Display () = 

        let window = new Window()
        do window.Height <- 600.00
           window.Width <- 800.00

Keep in mind that any other code that does execution must also be indented with the do, like the window.Width <- 800.00 is.

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