F#でWPF --- フォルダダイアログCommand

下記記事にてOpenFileDialogに対応したActionを作成しました。
F#でWPF --- ファイルダイアログCommand - 何でもプログラミング

今回はフォルダを選択するダイアログに対応したActionを作成します。

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

ボタンを押してフォルダダイアログを開き、パスを選択するとテキストボックスにパスが表示されるアプリケーションを作成します。

f:id:any-programming:20170217230441p:plain

参照の追加

今回はSystem.Windows.Forms.FolderBrowserDialogを利用するため、System.Windows.Forms.dllを参照に追加します。

System.Windows.FormsはWPFのコントロールと名前が衝突しやすいので、open System.Windows.Formsを利用しないことをお勧めします。

f:id:any-programming:20170217225245p:plain

FolderDialogAction

ダイアログを開いたときに指定のフォルダが選択されているようにするには、SelectedPathにパスを設定しておきます。

namespace Actions

open System.Windows
open System.Windows.Input
open System.Windows.Interactivity

type FolderDialogAction() = 
    inherit TriggerAction<FrameworkElement>()

    static member val CommandProperty = DependencyProperty.Register("Command", typeof<ICommand>, typeof<FolderDialogAction>)
    member this.Command with get()           = this.GetValue(FolderDialogAction.CommandProperty) :?> ICommand
                        and  set(x:ICommand) = this.SetValue(FolderDialogAction.CommandProperty, x)

    static member val InitialPathProperty = DependencyProperty.Register("InitialPath", typeof<string>, typeof<FolderDialogAction>)
    member this.InitialPath with get()         = this.GetValue(FolderDialogAction.InitialPathProperty) :?> string
                            and  set(x:string) = this.SetValue(FolderDialogAction.InitialPathProperty, x)

    override this.Invoke parameter = 
        use dialog = new System.Windows.Forms.FolderBrowserDialog(SelectedPath = this.InitialPath)
        if dialog.ShowDialog() = System.Windows.Forms.DialogResult.OK && this.Command <> null then
            this.Command.Execute dialog.SelectedPath


アプリケーションコード

F#側はファイルダイアログCommandの時と同じです。

Xaml

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
        xmlns:local="clr-namespace:Actions;assembly=FolderDialogAction"
        Title="MainWindow" Height="80" Width="300">
    <Grid>
        <Button Content="フォルダダイアログ" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="100">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <local:FolderDialogAction Command="{Binding SetPath}" InitialPath="C:\src" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
        <TextBlock Text="{Binding Path}" HorizontalAlignment="Left" Margin="115,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
    </Grid>
</Window>