F#でWPF --- ウィンドウ表示

F# & WPFのプロジェクトテンプレートはいくつか存在するみたいですが、(F# Empty Windows App (WPF) 等)今回はコンソールアプリケーションから作成していきたいと思います。

プロジェクトの作成

Console Applicationを選択します。
f:id:any-programming:20170121100902p:plain

参照の追加

PresentationCore、PresentationFramework、System.Xaml、UIAutomationTypes、WindowsBaseの5つを参照に追加します。
f:id:any-programming:20170121101713p:plain

Xamlファイルの追加

ファイルの追加で、Xamlファイルは存在しないので、適当にXmlファイルを選択して名称の拡張子をxamlにします。
f:id:any-programming:20170121102239p:plain

Xamlファイルのビルドアクション変更

ビルドアクションをResourceに変更します。(EmbeddedResourceにしてGetManifestResourceStreamで読み込んでもOKです。今回はResourceで進めます。)
f:id:any-programming:20170121103000p:plain

Xamlを編集

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="MainWindow" Height="350" Width="525">
</Window>


Program.fsを編集

STAThread属性を忘れやすいので気を付けてください。

open System
open System.Windows

[<STAThread>]
[<EntryPoint>]
let main argv = 
    let window = Application.LoadComponent(Uri("MainWindow.xaml", UriKind.Relative)) :?> Window
    Application().Run(window) |> ignore
    0


実行

コンソールとWPFウィンドウが立ち上がります。
f:id:any-programming:20170121111954p:plain

コンソールを消す

プロジェクトの設定で、Output typeをWindows Applicationに変更します。
f:id:any-programming:20170121112216p:plain

コントロールの追加

ボタンを押したらテキストボックスをクリアする簡単なサンプルを実装します。

Xaml

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="75" Width="230">
    <Grid>
        <Button x:Name="button" Content="Clear" HorizontalAlignment="Left" Margin="135,13,0,0" VerticalAlignment="Top" Width="75"/>
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="10,12,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
    </Grid>
</Window>

F#

open System
open System.Windows
open System.Windows.Controls

[<STAThread>]
[<EntryPoint>]
let main argv = 
    let window = Application.LoadComponent(Uri("MainWindow.xaml", UriKind.Relative)) :?> Window

    let button = window.FindName("button") :?> Button
    let textBox = window.FindName("textBox") :?> TextBox
    
    button.Click 
    |> Event.add (fun _ -> textBox.Text <- "")

    Application().Run(window) |> ignore
    0

実行
f:id:any-programming:20170121113832p:plain