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

时间:2009-11-08 22:30:36

标签: data-binding f# inotifypropertychanged

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

2 个答案:

答案 0 :(得分:18)

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

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

答案 1 :(得分:1)

https://github.com/Fody/PropertyChanged https://github.com/Fody/PropertyChanged/issues/280

在实践中

您可以使用更改过的表情属性来自动实施

public abstract class ViewModelBase :  INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    }

然后您可以像这样使用它

type ViewModelTest() =
    inherit ViewModelBase()

    /// two way binding
    member val Hello = 6 with get, set

    /// one way binding
    member x.Yes = x.Hello + 1

生成的反编译代码为

using System;
using Microsoft.FSharp.Core;

namespace Shrimp.UI.Forms.FSharp
{
    // Token: 0x02000002 RID: 2
    [CompilationMapping(3)]
    [Serializable]
    public class ViewModelTest : ViewModelBase
    {
        // Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250
        public ViewModelTest() : this()
        {
            this.Hello@ = 6;
        }

        // Token: 0x17000001 RID: 1
        // (get) Token: 0x06000002 RID: 2 RVA: 0x00002061 File Offset: 0x00000261
        // (set) Token: 0x06000003 RID: 3 RVA: 0x0000206C File Offset: 0x0000026C
        public int Hello
        {
            get
            {
                return this.Hello@;
            }
            set
            {
                if (this.Hello@ == value)
                {
                    return;
                }
                this.Hello@ = value;
                this.<>OnPropertyChanged(<>PropertyChangedEventArgs.Yes);
                this.<>OnPropertyChanged(<>PropertyChangedEventArgs.Hello);
            }
        }

        // Token: 0x17000002 RID: 2
        // (get) Token: 0x06000004 RID: 4 RVA: 0x000020A4 File Offset: 0x000002A4
        public int Yes
        {
            get
            {
                return this.Hello + 1;
            }
        }

        // Token: 0x04000001 RID: 1
        internal int Hello@;
    }
}