问题 F#:使用INotifyPropertyChanged进行数据绑定


如何实现INotifyPropertyChanged以用于F#类型? 谢谢!


4948
2017-11-08 22:30


起源



答案:


它与任何其他语言基本相同:

open System.ComponentModel
type MyType() =
  let ev = new Event<_,_>()
  let mutable str = ""
  member x.StringProp
    with get() = str
     and set(str') =
       str <- str'
       ev.Trigger(x, PropertyChangedEventArgs("StringProp"))
  interface INotifyPropertyChanged with
    [<CLIEvent>]
    member x.PropertyChanged = ev.Publish

15
2017-11-08 22:58



这与其他语言“基本相同”:P - Cameron MacFarland
谢谢,[<CLIEvent>]属性究竟是什么?我似乎无法找到任何文件。 - rysama
@RodYan - 它影响事件所采用的编译形式;为了与其他.NET语言互操作(并实现暴露.NET事件的接口),您需要将其应用于IEvent值。这导致 add_ 和 remove_ 要生成的方法,而不是实际公开类型的属性 IEvent<_,_>,如描述 msdn.microsoft.com/en-us/library/ee370437(VS.100).aspx。 - kvb
另外一个选择 fssnip.net/4Q - Maslow
这是实现接口的一个很好的例子,但没有说明如何通过数据绑定将其连接到WPF控件属性。 - Scott Hutchinson


答案:


它与任何其他语言基本相同:

open System.ComponentModel
type MyType() =
  let ev = new Event<_,_>()
  let mutable str = ""
  member x.StringProp
    with get() = str
     and set(str') =
       str <- str'
       ev.Trigger(x, PropertyChangedEventArgs("StringProp"))
  interface INotifyPropertyChanged with
    [<CLIEvent>]
    member x.PropertyChanged = ev.Publish

15
2017-11-08 22:58



这与其他语言“基本相同”:P - Cameron MacFarland
谢谢,[<CLIEvent>]属性究竟是什么?我似乎无法找到任何文件。 - rysama
@RodYan - 它影响事件所采用的编译形式;为了与其他.NET语言互操作(并实现暴露.NET事件的接口),您需要将其应用于IEvent值。这导致 add_ 和 remove_ 要生成的方法,而不是实际公开类型的属性 IEvent<_,_>,如描述 msdn.microsoft.com/en-us/library/ee370437(VS.100).aspx。 - kvb
另外一个选择 fssnip.net/4Q - Maslow
这是实现接口的一个很好的例子,但没有说明如何通过数据绑定将其连接到WPF控件属性。 - Scott Hutchinson