Dependency Property in F#

2019-07-11 04:48发布

问题:

I have an MVVM app written in F# and one of the main problems which I have faced was closing of modal dialogs. I decided to subscribe to an viewmodel's RequestedClose event in view, but problem of DialogResult still remained. So, I decided to bind DialogResult to viewmodel's property, but soon I realized that DialogResult is not a DependencyProperty. Eventually I tried to implement this accepted answer. But I couldn't get it to work... Here's my code:

type DialogCloser() =

static let DialogResultProperty =
    DependencyProperty.RegisterAttached("DialogResult", typeof<bool>, typeof<DialogCloser>)

member this.GetDialogResult (a:DependencyObject) = a.GetValue(DialogResultProperty) :?> bool

member this.SetDialogResult (a:DependencyObject) (value:string) = a.SetValue(DialogResultProperty, value)

member this.DialogResultChanged (a:DependencyObject) (e:DependencyPropertyChangedEventArgs) =
    let window = a :?> Window
    match window with
    | null -> failwith "Not a Window"
    | _ -> window.DialogResult <- System.Nullable(e.NewValue :?> bool)

Also I've tried something like this, but it didn't work for me as well. I've faced with two types of exceptions: 1) DialogResult not found in DialogCloser 2) And, if I add DialogResult property with get and set, DialogResult can't be applied to something that is not a DialogCloser.

P.S: I know that there's must be an another way of solving this problem instead of making an Attached Property, but for further development I need to understand how to do this properly in F#.

标签: .net wpf xaml mvvm f#