Sök…


Introduktion

Målet här är att bygga en enkel applikation i F # med Windows Presentation Foundation (WPF) med traditionella menyer och dialogrutor. Det härstammar från min frustration över att försöka vada hundratals avsnitt av dokumentation, artiklar och inlägg som handlar om F # och WPF. För att göra något med WPF verkar du behöva veta allt om det. Mitt syfte är att tillhandahålla ett möjligt sätt in, ett enkelt skrivbordsprojekt som kan fungera som en mall för dina appar.

Ställ in projektet

Vi antar att du gör detta i Visual Studio 2015 (VS 2015 Community, i mitt fall). Skapa ett tomt konsolprojekt i VS. I projekt | Egenskaper ändrar utgångstyp till Windows-applikation.

Därefter använder du NuGet för att lägga till FsXaml.Wpf i projektet; detta paket skapades av den uppskattade Reed Copsey, Jr., och det förenklar i hög grad att använda WPF från F #. Vid installationen kommer det att lägga till ett antal andra WPF-enheter, så du behöver inte göra det. Det finns andra liknande paket som FsXaml, men ett av mina mål var att hålla antalet verktyg så litet som möjligt för att göra det övergripande projektet så enkelt och underhållbart som möjligt.

Lägg till UIAutomationTypes som referens. det kommer som en del av .NET.

Lägg till "Business Logic"

Antagligen kommer ditt program att göra något. Lägg till din arbetskod till projektet istället för Program.fs. I detta fall är vår uppgift att rita spirografkurvor på en fönsterduk. Detta utförs med hjälp av Spirograph.fs nedan.

namespace Spirograph

// open System.Windows does not automatically open all its sub-modules, so we 
// have to open them explicitly as below, to get the resources noted for each.
open System                             // for Math.PI
open System.Windows                     // for Point
open System.Windows.Controls            // for Canvas
open System.Windows.Shapes              // for Ellipse
open System.Windows.Media               // for Brushes

// ------------------------------------------------------------------------------
// This file is first in the build sequence, so types should be defined here
type DialogBoxXaml  = FsXaml.XAML<"DialogBox.xaml">
type MainWindowXaml = FsXaml.XAML<"MainWindow.xaml">
type App            = FsXaml.XAML<"App.xaml"> 

// ------------------------------------------------------------------------------
// Model: This draws the Spirograph
type MColor = | MBlue   | MRed | MRandom

type Model() =
  let mutable myCanvas: Canvas = null
  let mutable myR              = 220    // outer circle radius
  let mutable myr              = 65     // inner circle radius
  let mutable myl              = 0.8    // pen position relative to inner circle
  let mutable myColor          = MBlue  // pen color
  
  let rng                      = new Random()
  let mutable myRandomColor    = Color.FromRgb(rng.Next(0, 255) |> byte,
                                               rng.Next(0, 255) |> byte,
                                               rng.Next(0, 255) |> byte)

  member this.MyCanvas
    with get() = myCanvas
    and  set(newCanvas) = myCanvas <- newCanvas

  member this.MyR
    with get() = myR
    and  set(newR) = myR <- newR

  member this.Myr
    with get() = myr
    and  set(newr) = myr <- newr

  member this.Myl
    with get() = myl
    and  set(newl) = myl <- newl

  member this.MyColor
    with get() = myColor
    and  set(newColor) = myColor <- newColor

  member this.Randomize =
    // Here we randomize the parameters. You can play with the possible ranges of
    // the parameters to find randomized spirographs that are pleasing to you.
    this.MyR      <- rng.Next(100, 500)
    this.Myr      <- rng.Next(this.MyR / 10, (9 * this.MyR) / 10)
    this.Myl      <- 0.1 + 0.8 * rng.NextDouble()
    this.MyColor  <- MRandom
    myRandomColor <- Color.FromRgb(rng.Next(0, 255) |> byte,
                                   rng.Next(0, 255) |> byte,
                                   rng.Next(0, 255) |> byte)

  member this.DrawSpirograph =
    // Draw a spirograph. Note there is some fussing with ints and floats; this 
    // is required because the outer and inner circle radii are integers. This is
    // necessary in order for the spirograph to return to its starting point 
    // after a certain number of revolutions of the outer circle.
    
    // Start with usual recursive gcd function and determine the gcd of the inner
    // and outer circle radii. Everything here should be in integers.
    let rec gcd x y =
        if y = 0 then x
        else gcd y (x % y)
  
    let g = gcd this.MyR this.Myr             // find greatest common divisor
    let maxRev = this.Myr / g                 // maximum revs to repeat

    // Determine width and height of window, location of center point, scaling 
    // factor so that spirograph fits within the window, ratio of inner and outer
    // radii.
    
    // Everything from this point down should be float.
    let width, height = myCanvas.ActualWidth, myCanvas.ActualHeight
    let cx, cy = width / 2.0, height / 2.0    // coordinates of center point
    let maxR   = min cx cy                    // maximum radius of outer circle
    let scale  = maxR / float(this.MyR)             // scaling factor
    let rRatio = float(this.Myr) / float(this.MyR)  // ratio of the radii

    // Build the collection of spirograph points, scaled to the window.
    let points = new PointCollection()
    for degrees in [0 .. 5 .. 360 * maxRev] do
      let angle = float(degrees) * Math.PI / 180.0
      let x, y = cx + scale * float(this.MyR) *
                 ((1.0-rRatio)*Math.Cos(angle) +
                  this.Myl*rRatio*Math.Cos((1.0-rRatio)*angle/rRatio)),
                 cy + scale * float(this.MyR) *
                 ((1.0-rRatio)*Math.Sin(angle) - 
                  this.Myl*rRatio*Math.Sin((1.0-rRatio)*angle/rRatio))
      points.Add(new Point(x, y))
  
    // Create the Polyline with the above PointCollection, erase the Canvas, and 
    // add the Polyline to the Canvas Children
    let brush = match this.MyColor with
                | MBlue   -> Brushes.Blue
                | MRed    -> Brushes.Red
                | MRandom -> new SolidColorBrush(myRandomColor)
  
    let mySpirograph = new Polyline()
    mySpirograph.Points <- points
    mySpirograph.Stroke <- brush

    myCanvas.Children.Clear()
    this.MyCanvas.Children.Add(mySpirograph) |> ignore

Spirograph.fs är den första F # -filen i sammanställningsordningen, så den innehåller definitionerna av de typer vi behöver. Dess uppgift är att rita en spirograf på huvudfönstret Canvas baserat på parametrar som anges i en dialogruta. Eftersom det finns många referenser om hur man ritar en spirograf kommer vi inte att gå in på det här.

Skapa huvudfönstret i XAML

Du måste skapa en XAML-fil som definierar huvudfönstret som innehåller vår meny och ritningsutrymme. Här är XAML-koden i MainWindow.xaml:

<!-- This defines the main window, with a menu and a canvas. Note that the Height
     and Width are overridden in code to be 2/3 the dimensions of the screen -->
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Spirograph" Height="200" Width="300">
    <!-- Define a grid with 3 rows: Title bar, menu bar, and canvas. By default
         there is only one column -->
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <!-- Define the menu entries -->
        <Menu  Grid.Row="0">
            <MenuItem Header="File">
                <MenuItem Header="Exit"
                          Name="menuExit"/>
            </MenuItem>
            <MenuItem Header="Spirograph">
                <MenuItem Header="Parameters..."
                          Name="menuParameters"/>
                <MenuItem Header="Draw"
                          Name="menuDraw"/>
            </MenuItem>
            <MenuItem Header="Help">
                <MenuItem Header="About"
                          Name="menuAbout"/>
            </MenuItem>
        </Menu>
        <!-- This is a canvas for drawing on. If you don't specify the coordinates
             for Left and Top you will get NaN for those values -->
        <Canvas Grid.Row="1" Name="myCanvas" Left="0" Top="0">
        </Canvas>
    </Grid>
</Window>

Kommentarer ingår vanligtvis inte i XAML-filer, vilket jag tror är ett misstag. Jag har lagt till några kommentarer till alla XAML-filer i detta projekt. Jag hävdar inte att det är de bästa kommentarerna som någonsin skrivits, men de visar åtminstone hur en kommentar ska formateras. Observera att kapslade kommentarer inte är tillåtna i XAML.

Skapa dialogrutan i XAML och F #

XAML-filen för spirografparametrarna finns nedan. Det innehåller tre textrutor för spirografparametrarna och en grupp med tre radioknappar för färg. När vi ger radioknappar samma gruppnamn - som vi har här - hanterar WPF på / av-omkopplingen när en är vald.

<!-- This first part is boilerplate, except for the title, height and width.
     Note that some fussing with alignment and margins may be required to get
     the box looking the way you want it. -->
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Parameters" Height="200" Width="250">
    <!-- Here we define a layout of 3 rows and 2 columns below the title bar -->
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <!-- Define a label and a text box for the first three rows. Top row is
             the integer radius of the outer circle -->
        <StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="0" 
                    Grid.ColumnSpan="2">
            <Label VerticalAlignment="Top" Margin="5,6,0,1" Content="R: Outer" 
                   Height="24" Width='65'/>
            <TextBox x:Name="radiusR"  Margin="0,0,0,0.5" Width="120" 
                     VerticalAlignment="Bottom" Height="20">Integer</TextBox>
        </StackPanel>
        <!-- This defines a label and text box for the integer radius of the
             inner circle -->
        <StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="1" 
                    Grid.ColumnSpan="2">
            <Label VerticalAlignment="Top" Margin="5,6,0,1" Content="r: Inner" 
                   Height="24" Width='65'/>
            <TextBox x:Name="radiusr"  Margin="0,0,0,0.5" Width="120" 
                     VerticalAlignment="Bottom" Height="20" Text="Integer"/>
        </StackPanel>
        <!-- This defines a label and text box for the float ratio of the inner
             circle radius at which the pen is positioned -->
        <StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="2" 
                    Grid.ColumnSpan="2">
            <Label VerticalAlignment="Top" Margin="5,6,0,1" Content="l: Ratio" 
                   Height="24" Width='65'/>
            <TextBox x:Name="ratiol"  Margin="0,0,0,1" Width="120" 
                     VerticalAlignment="Bottom" Height="20" Text="Float"/>
        </StackPanel>
        <!-- This defines a radio button group to select color -->
        <StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="3" 
                    Grid.ColumnSpan="2">
            <Label VerticalAlignment="Top" Margin="5,6,4,5.333" Content="Color" 
                   Height="24"/>
            <RadioButton x:Name="buttonBlue" Content="Blue" GroupName="Color" 
                         HorizontalAlignment="Left"  VerticalAlignment="Top"
                         Click="buttonBlueClick"
                         Margin="5,13,11,3.5" Height="17"/>
            <RadioButton x:Name="buttonRed"  Content="Red"  GroupName="Color" 
                         HorizontalAlignment="Left" VerticalAlignment="Top"
                         Click="buttonRedClick"
                         Margin="5,13,5,3.5" Height="17" />
            <RadioButton x:Name="buttonRandom"  Content="Random"  
                         GroupName="Color" Click="buttonRandomClick"
                         HorizontalAlignment="Left" VerticalAlignment="Top"
                         Margin="5,13,5,3.5" Height="17" />
        </StackPanel>
        <!-- These are the standard OK/Cancel buttons -->
        <Button Grid.Row="4" Grid.Column="0" Name="okButton" 
                Click="okButton_Click" IsDefault="True">OK</Button>
        <Button Grid.Row="4" Grid.Column="1" Name="cancelButton" 
                IsCancel="True">Cancel</Button>
    </Grid>
</Window>

Nu lägger vi till koden bakom Dialog.Box. I enlighet med konventionen heter den kod som används för att hantera gränssnittet i dialogrutan med resten av programmet XXX.xaml.fs, där den tillhörande XAML-filen heter XXX.xaml.

namespace Spirograph

open System.Windows.Controls

type DialogBox(app: App, model: Model, win: MainWindowXaml) as this =
  inherit DialogBoxXaml()

  let myApp   = app
  let myModel = model
  let myWin   = win
  
  // These are the default parameters for the spirograph, changed by this dialog
  // box
  let mutable myR = 220                 // outer circle radius
  let mutable myr = 65                  // inner circle radius
  let mutable myl = 0.8                 // pen position relative to inner circle
  let mutable myColor = MBlue           // pen color

  // These are the dialog box controls. They are initialized when the dialog box
  // is loaded in the whenLoaded function below.
  let mutable RBox: TextBox = null
  let mutable rBox: TextBox = null
  let mutable lBox: TextBox = null

  let mutable blueButton: RadioButton   = null
  let mutable redButton: RadioButton    = null
  let mutable randomButton: RadioButton = null

  // Call this functions to enable or disable parameter input depending on the
  // state of the randomButton. This is a () -> () function to keep it from
  // being executed before we have loaded the dialog box below and found the
  // values of TextBoxes and RadioButtons.
  let enableParameterFields(b: bool) = 
    RBox.IsEnabled <- b
    rBox.IsEnabled <- b
    lBox.IsEnabled <- b

  let whenLoaded _ =
    // Load and initialize text boxes and radio buttons to the current values in 
    // the model. These are changed only if the OK button is clicked, which is 
    // handled below. Also, if the color is Random, we disable the parameter
    // fields.
    RBox <- this.FindName("radiusR") :?> TextBox
    rBox <- this.FindName("radiusr") :?> TextBox
    lBox <- this.FindName("ratiol")  :?> TextBox

    blueButton   <- this.FindName("buttonBlue")   :?> RadioButton
    redButton    <- this.FindName("buttonRed")    :?> RadioButton
    randomButton <- this.FindName("buttonRandom") :?> RadioButton

    RBox.Text <- myModel.MyR.ToString()
    rBox.Text <- myModel.Myr.ToString()
    lBox.Text <- myModel.Myl.ToString()

    myR <- myModel.MyR
    myr <- myModel.Myr
    myl <- myModel.Myl
  
    blueButton.IsChecked   <- new System.Nullable<bool>(myModel.MyColor = MBlue)
    redButton.IsChecked    <- new System.Nullable<bool>(myModel.MyColor = MRed)
    randomButton.IsChecked <- new System.Nullable<bool>(myModel.MyColor = MRandom)
   
    myColor <- myModel.MyColor
    enableParameterFields(not (myColor = MRandom))

  let whenClosing _ =
    // Show the actual spirograph parameters in a message box at close. Note the 
    // \n in the sprintf gives us a linebreak in the MessageBox. This is mainly
    // for debugging, and it can be deleted.
    let s = sprintf "R = %A\nr = %A\nl = %A\nColor = %A" 
                    myModel.MyR myModel.Myr myModel.Myl myModel.MyColor
    System.Windows.MessageBox.Show(s, "Spirograph") |> ignore
    ()
  
  let whenClosed _ =
    () 
  
  do 
    this.Loaded.Add whenLoaded
    this.Closing.Add whenClosing
    this.Closed.Add whenClosed

  override this.buttonBlueClick(sender: obj, 
                                eArgs: System.Windows.RoutedEventArgs) =
    myColor <- MBlue
    enableParameterFields(true)
    () 
  
  override this.buttonRedClick(sender: obj, 
                               eArgs: System.Windows.RoutedEventArgs) =
    myColor <- MRed      
    enableParameterFields(true)
    () 
  
  override this.buttonRandomClick(sender: obj, 
                                  eArgs: System.Windows.RoutedEventArgs) =
    myColor <- MRandom
    enableParameterFields(false)
    () 
  
  override this.okButton_Click(sender: obj,
                               eArgs: System.Windows.RoutedEventArgs) =
    // Only change the spirograph parameters in the model if we hit OK in the 
    // dialog box.
    if myColor = MRandom
    then myModel.Randomize
    else myR <- RBox.Text |> int
         myr <- rBox.Text |> int
         myl <- lBox.Text |> float

         myModel.MyR   <- myR
         myModel.Myr   <- myr
         myModel.Myl   <- myl
         model.MyColor <- myColor

    // Note that setting the DialogResult to nullable true is essential to get
    // the OK button to work.
    this.DialogResult <- new System.Nullable<bool> true         
    () 

Mycket av koden här ägnas åt att se till att spirografparametrarna i Spirograph.fs matchar de som visas i denna dialogruta. Observera att det inte finns något felkontroll: Om du anger en flytande punkt för de heltal som förväntas i de två bästa fältet kommer programmet att krascha. Så lägg till felkontroll i din egen insats.

Observera också att parameterinmatningsfält är inaktiverade med slumpmässig färg väljs i radioknapparna. Det är här bara för att visa hur det kan göras.

För att flytta data fram och tillbaka mellan dialogrutan och programmet använder jag System.Windows.Element.FindName () för att hitta rätt kontroll, kasta den till den kontroll som den ska vara och sedan få relevanta inställningar från Kontrollera. De flesta andra exempelprogram använder databindning. Jag gjorde det inte av två skäl: För det första kunde jag inte ta reda på hur det skulle fungera, och för det andra, när det inte fungerade fick jag inget felmeddelande av något slag. Kanske någon som besöker detta på StackOverflow kan berätta för mig hur man använder databindning utan att ta med en helt ny uppsättning NuGet-paket.

Lägg till koden bakom MainWindow.xaml

namespace Spirograph

type MainWindow(app: App, model: Model) as this =
  inherit MainWindowXaml()

  let myApp   = app
  let myModel = model
  
  let whenLoaded _ =
    ()
  
  let whenClosing _ =
    ()
  
  let whenClosed _ =
    () 
  
  let menuExitHandler _ = 
    System.Windows.MessageBox.Show("Good-bye", "Spirograph") |> ignore
    myApp.Shutdown()
    () 
  
  let menuParametersHandler _ = 
    let myParametersDialog = new DialogBox(myApp, myModel, this)
    myParametersDialog.Topmost <- true
    let bResult = myParametersDialog.ShowDialog()
    myModel.DrawSpirograph
    () 
  
  let menuDrawHandler _ = 
    if myModel.MyColor = MRandom then myModel.Randomize
    myModel.DrawSpirograph
    () 
  
  let menuAboutHandler _ = 
    System.Windows.MessageBox.Show("F#/WPF Menus & Dialogs", "Spirograph") 
    |> ignore
    () 
  
  do          
    this.Loaded.Add whenLoaded
    this.Closing.Add whenClosing
    this.Closed.Add whenClosed
    this.menuExit.Click.Add menuExitHandler
    this.menuParameters.Click.Add menuParametersHandler
    this.menuDraw.Click.Add menuDrawHandler
    this.menuAbout.Click.Add menuAboutHandler

Det här händer inte mycket: Vi öppnar dialogrutan Parametrar när det behövs och vi har möjlighet att rita om spirografen med vad nuvarande parametrar är.

Lägg till App.xaml och App.xaml.fs för att binda allt ihop

<!-- All boilerplate for now -->
<Application 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"               
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">      
    <Application.Resources>      
    </Application.Resources>  
</Application>

Här är koden bakom:

namespace Spirograph

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

module Main = 
  [<STAThread; EntryPoint>]
  let main _ =
    // Create the app and the model with the "business logic", then create the
    // main window and link its Canvas to the model so the model can access it.
    // The main window is linked to the app in the Run() command in the last line.
    let app = App()
    let model = new Model()
    let mainWindow = new MainWindow(app, model) 
    model.MyCanvas <- (mainWindow.FindName("myCanvas") :?> Canvas)         
    
    // Make sure the window is on top, and set its size to 2/3 of the dimensions 
    // of the screen.
    mainWindow.Topmost <- true
    mainWindow.Height  <- 
      (System.Windows.SystemParameters.PrimaryScreenHeight * 0.67)
    mainWindow.Width   <- 
      (System.Windows.SystemParameters.PrimaryScreenWidth * 0.67) 
    
    app.Run(mainWindow) // Returns application's exit code.

App.xaml är alla pannplattor här, främst för att visa var applikationsresurser, till exempel ikoner, grafik eller externa filer - kan deklareras. Kameran App.xaml.fs drar ihop modellen och MainWindow, storlekar MainWindow till två tredjedelar av den tillgängliga skärmstorleken och kör den.

När du bygger detta, kom ihåg att se till att egenskapen Build för varje xaml-fil är inställd på Resource. Då kan du antingen köra igenom felsökningen eller kompilera till en exe-fil. Observera att du inte kan köra detta med F # -tolkaren: FsXaml-paketet och tolkaren är inkompatibla.

Där har du det. Jag hoppas att du kan använda detta som en utgångspunkt för dina egna applikationer och genom att göra det kan du utöka din kunskap utöver vad som visas här. Eventuella kommentarer och förslag kommer att uppskattas.



Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow