使用FSharp.ViewModule启用对话框确定按钮

时间:2016-12-02 08:30:48

标签: wpf mvvm f# fsharp.viewmodule

我有一个简单的对话框,其中有两个字段用于输入一个人的姓名和地址,我只希望在他们都有值时启用OK按钮。以下是我的观点的相关部分:

<TextBox Text="{Binding Name}" ... />
<TextBox Text="{Binding Address}" ... />
<Button Content="OK" IsEnabled="{Binding OK, Mode=OneWay}" ... />

这是我的观点模型:

namespace ViewModels

open FSharp.ViewModule
open FSharp.ViewModule.Validation
open FsXaml

type DialogView = XAML<"Dialog.xaml">

type DialogVM() as self =
    inherit ViewModelBase()  

    let name = self.Factory.Backing( <@ self.Name @>, "", notNullOrWhitespace )
    let address = self.Factory.Backing( <@ self.Address @>, "" )

    let hasValue str = not( System.String.IsNullOrWhiteSpace( str ))

    member x.Name 
        with get() = name.Value 
        and set value = name.Value <- value ; self.RaisePropertyChanged( <@ self.OK @> )
    member x.Address 
        with get() = address.Value 
        and set value = address.Value <- value ; self.RaisePropertyChanged( <@ self.OK @> )
    member x.OK with get() = hasValue x.Name && hasValue x.Address

但是OK按钮始终处于启用状态。我做错了什么?

1 个答案:

答案 0 :(得分:3)

问题在于TextBox.Text = LostFocus的默认绑定模式。 该物业尚未更新。

所以:

    <TextBox Text="{Binding Name,UpdateSourceTrigger=PropertyChanged}"/>
    <TextBox Text="{Binding Address,UpdateSourceTrigger=PropertyChanged}" />

但FSharp.ViewModule中有一些东西让你的生活更轻松。在您的情况下,它是属性IsValid

let name = self.Factory.Backing( <@ self.Name @>, "", notNullOrWhitespace)
let address = self.Factory.Backing( <@ self.Address @>, "", notNullOrWhitespace)

member x.Name 
    with get() = name.Value 
    and set value = name.Value <- value
member x.Address 
    with get() = address.Value 
    and set value = address.Value <- value

在XAML中:

<Button Content="OK" IsEnabled="{Binding IsValid}"  />