Ndc magazine 1 issue

Page 25

SETTING UP THE EVENT HANDLERS In addition to publishing the PropertyChanged event, the UnformattedText textbox obtains knowledge of each new character by checking for the KeyUp event in the textbox, and then setting the property in the ViewModel to the current value of the textbox text. This happens in the app.fs module, as part of the loadWindow method. Also contained in the loadWindow method is the event handler for the PropertyChanged events, which updates the text for the FormattedTextBox. Because that textbox is read-only, there is no backing property, just a call to the GetFormattedText method. This is called when any of the properties change, because all three affect the final output of the FormattedTextBox. let loadWindow() = _viewModel.PropertyChanged |> Event.add (fun _ -> window.FormattedTextBox.Document <- _viewModel.GetFormattedText) window.UnformattedTextBox.KeyUp.Add(fun _ -> _viewModel.Text <- window.UnformattedTextBox.Text)

IMPLEMENTING THE TEXT FORMATTING This GetFormattedText method is the heart of the application. First, it checks the incoming string of text for vowels via the CheckForVowels method in the application’s Model. let private isVowel isWvowel isYvowel character = let isV = match character with | 'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U'-> true | 'w' | 'W' when isWvowel -> true | 'y' | 'Y' when isYvowel -> true | _ -> false (character, isV) let CheckForVowels isWvowel isYvowel text = Array.map (isVowel isWvowel isYvowel) text

Then, that information is sent to the BuildDocument and associated ConvertText methods, which create a new instance of the Run class for each character, color the text appropriately, and then add all of them to a new FlowDocument. The FormattedTextBox then takes the new FlowDocument as its text property. If you are new to the RichTextBox in WPF, the Run class works very much like an html <span> tag to format small sections of inline text (in our case, a single character) without adding additional spacing. These Runs must be added to a paragraph, which creates a full block of text (i.e., not inline). The paragraph may then be added to the FlowDocument is one of the top-level elements that gather text into a document for displaying. Specifically, it allows dynamic reformatting for different content sizes – in other words, for a Responsive (capital-R) design, use a FlowDocument.

25


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.