F#でWPF --- チェックボックスCommand

今回はチェックボックスのCommandを利用したアプリケーションを作成します。

作成するアプリケーション

チェックを入れるとダイアログの背景がグレーに、外すと白になるアプリケーションを作成します。
f:id:any-programming:20170131235550p:plain

CommandParameter

チェックの状態をCommandと共に送るために、CommandParameterにIsCheckedの値を設定するようにします。

CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}}"


IsChecked

IsCheckedはデフォルトでTwoWayです。今回はsetterを利用しないのでModeをOneWayにします。

冗長ではありますが一貫した実装ができるため、入力は全てCommandにバインドし、その他は全てOneWayのバインドにすることを推奨します。

IsChecked="{Binding IsDark, Mode=OneWay}"


コード全体

F#で利用しているDataContextは下記記事を参照してください。
F#でWPF --- Elm Architectureを利用したMVVM - 何でもプログラミング

またF#でWPFプロジェクトを作成する方法は下記記事を参照してください。
F#でWPF --- ウィンドウ表示 - 何でもプログラミング

Xaml

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="MainWindow" Height="100" Width="200">
    <Grid Background="{Binding Background}">
        <CheckBox Content="背景を暗く" IsChecked="{Binding IsDark, Mode=OneWay}" Command="{Binding SetIsDark}" CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}}" HorizontalAlignment="Left" Margin="15,25,0,0" VerticalAlignment="Top"/>
    </Grid>
</Window>

F#

open System
open System.Windows
open System.Windows.Media

type Model = 
    { IsDark : bool }
    member this.Background = 
        match this.IsDark with
        | true  -> Brushes.LightGray
        | false -> Brushes.White

type Msg = SetIsDark of bool

let updateModel model msg =
    match msg with
    | SetIsDark x -> 
        { model with IsDark = x }

[<STAThread>]
[<EntryPoint>]
let main argv = 
    let window = Application.LoadComponent(Uri("MainWindow.xaml", UriKind.Relative)) :?> Window
    window.DataContext <- DataContext({ IsDark = false }, updateModel, id)
    Application().Run(window) |> ignore   
    0