建立新的表單類

來源:互聯網
上載者:User

標籤:style   blog   class   tar   ext   color   

建立新的表單類

 

到目前為止,我們看到的程式還只是指令碼風格,用現有的表單和控制項,快速把表單放在一起。這種編程風格可用於快速開發單一表單的應用程式,但是,對於快速建立有多個表單組成的應用程式,或者建立表單庫以用於其他 .NET 語言時,就會受到限制;在這些情況下,必須採取一種更面向組件(component-oriented)的方法。

通常,建立一個大型的 Windows  表單應用程式時,有一些表單需要重複使用;此外,通常希望這些表單能夠相互連信,通過調整彼此的屬性或調用彼此的方法。通常是定義新的表單類,從 System.Windows.Forms 派生,來實現的。清單 8-4 就是這樣一個例子,使用第五章介紹的類文法。

 

清單 8-4 建立新的表單類型

 

open System

openSystem.Windows.Forms

 

// aclass that derives from "Form" and add some user controls

type MyForm() as x =

  inherit Form(Width=174, Height=64)

 

  // create some controls to add the form

  let label = new Label(Top=8, Left=8, Width=40, Text="Input:")

  let textbox = new TextBox(Top=8, Left=48, Width=40)

  let button = new Button(Top=8, Left=96, Width=60, Text="Push Me!")

 

  // add a event to the button

  do button.Click.Add(fun _->

    let form = new MyForm(Text=textbox.Text)

    form.Show())

 

  // add the controls to the form

  do x.Controls.Add(label)

  do x.Controls.Add(textbox)

  do x.Controls.Add(button)

 

  // expose the text box as a property

  member x.Textbox = textbox

 

//create an new instance of our form

let form =

  let temp = new MyForm(Text="My Form")

  temp.Textbox.Text <- "Next!"

  temp

 

[<STAThread>]

do Application.Run(form)

 

圖 8-6 是前面代碼啟動並執行結果。

圖 8-6. 為便於重用而建立新表單類型

 

在前面的例子中,建立的表單有三個欄位:label、textbox 和 button;然後,就可以用外部代碼操作這些欄位。在樣本的最後,建立這個表單的執行個體,然後,設定其 textbox 欄位的 Text 屬性。

事件能公開表單的介面,非常像欄位。由於一些固有的限制,需要更多一點的工作。其思想是這樣的:建立一個新的事件,然後把這個事件儲存在類的一個欄位中,最後,把這個事件的訂閱發給篩選過的事件。下面的例子中,篩選 MouseClick 事件以建立 LeftMouseClick:

 

open System.Windows.Forms

 

// aform with addation LeftMouseClick event

type LeftClickForm() as x =

  inherit Form()

  // create the new event

  let event = new Event<MouseEventArgs>()

 

  // wire the new event up so it fires when the left

  // mouse button is clicked

  do x.MouseClick

  |> Event.filter (fun e-> e.Button =MouseButtons.Left)

  |> Event.add (fun e-> event.Trigger e)

 

  // expose the event as property

  [<CLIEvent>]

  member x.LeftMouseClick = event.Publish

 

以這種基於組件(component-based)的方式建立的表單,無疑要比以更指令碼化方式建立的表單容易使用;但是,在建立用於其他 .NET 語言的表單庫時,仍有缺陷。更多有關建立 F# 庫用於其他 .NET 語言的內容,參考第十三章。

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.