2016-03-23 43 views
-2

如何在不使用XAML的情況下使用F#和WPF創建Hello World應用程序?如何使用F#和WPF創建不使用XAML的Hello World應用程序?

具體來說,有什麼步驟來完成這個?

例如,我需要什麼文件啓動應用程序?

[更新]

我嘗試了一些建議,並收到以下錯誤:

enter image description here

我證實,該項目設置爲啓動項目。 我不知道我還需要做什麼。

+0

提示 - 'Library1.fs' - 爲什麼VS給出文件這個名字呢? –

+0

謝謝。我發佈了完整的答案。 –

回答

9

第一個要理解的是這個:XAML只是一個(據說更簡潔)的方式來表示一個對象圖。 (順便說一下,XAML不需要指定WPF UI,它可以用於其他事情...理論上)

XAML標記對應於實例化.NET類,屬性和嵌套標記對應於(大致)對象屬性。除此之外沒有什麼魔法。所有的XAML都會創建一堆對象並將它們連接在一起。

例如,這樣的:

<Button x:Name="myButton">Click!</Button> 

將粗略地對應於這樣的:

let myButton = Button(Content = "Click!") 

(它得到具有附加屬性,綁定類型轉換器等稍微複雜,但我不會在這裏進入所有)


第二個要知道的關鍵是如何編碼入口點。爲此,有三個簡單的步驟:

  1. 創建Application
  2. 創建Application.MainWindow
  3. 呼叫Application.Run

這裏是一個最小的全功能的應用程序(在的形式F#腳本):

#r "WindowsBase" 
#r "PresentationCore" 
#r "PresentationFramework" 

open System.Windows 
open System.Windows.Controls 

let button = Button(Content="Click me!") 
let label = Label(Content="Hello") 
button.Click.Add (fun _ -> label.Content <- "World") 

let layout = StackPanel() 
layout.Children.Add label 
layout.Children.Add button 

let window = 
    Window(
    Content = layout, 
    Visibility = Visibility.Visible) 

let app = Application(MainWindow = window) 
app.Run() 
+0

不,你沒有.. –

+0

oops。好的。它被保存了。 –

+1

你得開玩笑吧 –

1

若要建立在原始答案上:

我必須將項目的輸出庫設置爲Windows。

然後我不得不添加STAThread屬性。

下面的代碼:

module Temp 

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

[<STAThread>] do() 

let button = Button(Content="Click me!") 
let label = Label(Content="Hello") 
button.Click.Add (fun _ -> label.Content <- "World") 

let layout = StackPanel() 
layout.Children.Add label |> ignore 
layout.Children.Add button |> ignore 

let window = 
    Window(
    Content = layout, 
    Visibility = Visibility.Visible) 

let app = Application(MainWindow = window) 
app.Run() |> ignore 
相關問題