Traduction▲
Ce tutoriel est la traduction la plus fidèle possible du tutoriel original de Peter Bull, Microsoft Silverlight 4 - Rich Text Editor with Formatting, Printing, Open/Save and more.
Introduction▲
Créez un éditeur de texte riche en utilisant le contrôle RichTextArea avec des fonctions Ouvrir et Enregistrer, ainsi que des fonctions de mise en forme telles que Gras, Italique et Souligner avec Silverlight.
Éditeur de texte riche avec les fonctions pour la mise en forme, l'impression, ouvrir/enregistrer, etc.▲
Étape 1▲
Démarrez Microsoft Visual Web Developer 2010 Express, puis sélectionnez Fichier puis Nouveau Projet... Sélectionnez Visual Basic puis Application Silverlight dans les modèles installés, sélectionnez un emplacement si vous le souhaitez, puis entrez un nom pour le projet et appuyez sur OK :
Étape 2▲
Une nouvelle fenêtre Nouvelle application Silverlight devrait apparaître, décochez la case Héberger l'applicationSilverlightsur unnouveau site Web, puis sélectionnez la Version de Silverlight ciblée :
Étape 3 ▲
Une page vierge nommée MainPage.xaml devrait alors apparaître :

Étape 4 ▲
Sélectionnez Projet puis Ajouter une référence... La fenêtre Ajouter une référence devrait apparaître, sélectionnez System.Xml.Linq dans la liste .NET :
Étape 5▲
Ajouter la référence à System.Xml.Linq en cliquant sur OK.
Puis dans la section Tous les contrôles Silverlight de la Boîte à outils, sélectionnez le contrôle Canvas:
Étape 6▲
Dessinez un Canvassur la page, puis dans le volet XAML au-dessus de </Grid> modifiez la ligne Canvas1 comme ceci :
<Canvas Height="95" Width="400" VerticalAlignment="Top" HorizontalAlignment="Left" Name="Toolbar"></Canvas>Voir ci-dessous :

Étape 7▲
Puis dans la section Contrôles Silverlight communs de la Boîte à outils, sélectionnez le contrôle Button:
Étape 8▲
Dessinez huit boutons sur le Canvas en glissant les boutons de la Boite à outils sur le Canvas, puis dans le volet XAML entre les balises <Canvas> et </Canvas> modifiez les lignes <Button> comme ceci :
<Button Canvas.Left="6" Canvas.Top="6" Height="23" Width="75" Name="New" Content="New"/>
<Button Canvas.Left="87" Canvas.Top="6" Height="23" Width="75" Name="Open" Content="Open..."/>
<Button Canvas.Left="168" Canvas.Top="6" Height="23" Width="75" Name="Save" Content="Save..."/>
<Button Canvas.Left="249" Canvas.Top="6" Height="23" Width="75" Name="Print" Content="Print..."/>
<Button Canvas.Left="6" Canvas.Top="35" Height="23" Width="75" Name="Bold" Content="Bold"/>
<Button Canvas.Left="87" Canvas.Top="35" Height="23" Width="75" Name="Italic" Content="Italic"/>
<Button Canvas.Left="168" Canvas.Top="35" Height="23" Width="75" Name="Underline" Content="Underline"/>
<Button Canvas.Left="249" Canvas.Top="35" Height="23" Width="75" Name="TimeDate" Content="Time Date"/>Voir ci-dessous :

Étape 9▲
Étant toujours dans le volet XAML, en dessous de la balise </Canvas> et au-dessus de la balise </Grid> tapez le code ComboBox XAML suivant :
<ComboBox Canvas.Left="6" Canvas.Top="64" Height="23" Width="156" Name="Font"
FontFamily="{Binding SelectedItem.FontFamily, RelativeSource={RelativeSource Self}}"
FontSize="{Binding SelectedItem.FontSize, RelativeSource={RelativeSource Self}}">
<ComboBoxItem Content="Arial" Tag="Arial" FontFamily="Arial" FontSize="12" IsSelected="True"/>
<ComboBoxItem Content="Arial Black" Tag="Arial Black" FontFamily="Arial Black" FontSize="12"/>
<ComboBoxItem Content="Comic Sans MS" Tag="Comic Sans MS" FontFamily="Comic Sans MS" FontSize="12"/>
<ComboBoxItem Content="Courier New" Tag="Courier New" FontFamily="Courier New" FontSize="12"/>
<ComboBoxItem Content="Georgia" Tag="Georgia" FontFamily="Georgia" FontSize="12"/>
<ComboBoxItem Content="Lucida Sans Unicode" Tag="Lucida Sans Unicode" FontFamily="Lucida Sans Unicode" FontSize="12"/>
<ComboBoxItem Content="Times New Roman" Tag="Times New Roman" FontFamily="Times New Roman" FontSize="12"/>
<ComboBoxItem Content="Trebuchet MS" Tag="Trebuchet MS" FontFamily="Trebuchet MS" FontSize="12"/>
<ComboBoxItem Content="Verdana" Tag="Verdana" FontFamily="Verdana" FontSize="12"/>
<ComboBoxItem Content="Webdings" Tag="Webdings" FontSize="12"/>
</ComboBox>
<ComboBox Canvas.Left="168" Canvas.Top="64" Height="23" Width="75" Name="Size">
<ComboBoxItem Content="8" Tag="8"/>
<ComboBoxItem Content="10" Tag="10"/>
<ComboBoxItem Content="12" Tag="12"/>
<ComboBoxItem Content="16" Tag="16" IsSelected="True"/>
<ComboBoxItem Content="20" Tag="20"/>
<ComboBoxItem Content="24" Tag="24"/>
<ComboBoxItem Content="28" Tag="28"/>
<ComboBoxItem Content="36" Tag="36"/>
<ComboBoxItem Content="48" Tag="48"/>
<ComboBoxItem Content="72" Tag="72"/>
</ComboBox>
<ComboBox Canvas.Left="249" Canvas.Top="64" Height="23" Width="75" Name="Colour">
<ComboBoxItem Tag="FF000000" IsSelected="True">
<Rectangle Width="25" Height="14" Fill="Black"/>
</ComboBoxItem>
<ComboBoxItem Tag="FF808080">
<Rectangle Width="25" Height="14" Fill="Gray"/>
</ComboBoxItem>
<ComboBoxItem Tag="FFFF0000">
<Rectangle Width="25" Height="14" Fill="Red"/>
</ComboBoxItem>
<ComboBoxItem Tag="FFFFA500">
<Rectangle Width="25" Height="14" Fill="Orange"/>
</ComboBoxItem>
<ComboBoxItem Tag="FFFFFF00">
<Rectangle Width="25" Height="14" Fill="Yellow"/>
</ComboBoxItem>
<ComboBoxItem Tag="FF008000">
<Rectangle Width="25" Height="14" Fill="Green"/>
</ComboBoxItem>
<ComboBoxItem Tag="FF00FFFF">
<Rectangle Width="25" Height="14" Fill="Cyan"/>
</ComboBoxItem>
<ComboBoxItem Tag="FF0000FF">
<Rectangle Width="25" Height="14" Fill="Blue"/>
</ComboBoxItem>
<ComboBoxItem Tag="FFFF00FF">
<Rectangle Width="25" Height="14" Fill="Magenta"/>
</ComboBoxItem>
<ComboBoxItem Tag="FF800080">
<Rectangle Width="25" Height="14" Fill="Purple"/>
</ComboBoxItem>
</ComboBox>Voir ci-dessous :

Étape 10▲
Une fois de plus, en étant toujours dans le volet XAML, en dessous de la balise </Canvas> et au-dessus de la balise </Grid> tapez le code XAML suivant pour le contrôle RichTextArea :
<RichTextArea Height="205" Width="400" Margin="0,95,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"
TextWrapping="Wrap" BorderThickness="0" Name="Editor"/>Voir ci-dessous :

Étape 11▲
Faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Afficher le code. Dans la vue de code, au-dessus de la ligne Partial Public Class MainPage tapez le code suivant :
Imports System.Xml.Linq
Imports System.Windows.Printing
Étape 12▲
Puisque nous en sommes à la vue de code pour MainPage.xaml, en dessous du End Sub pour le constructeur Public Sub New() tapez le Sub suivant :
Private Sub Read(ByRef Stream As IO.Stream, ByRef Blocks As BlockCollection)
Dim _doc As XDocument = XDocument.Load(Stream)
Dim _colour As String
For Each _element As XElement In _doc.Descendants("Paragraph")
Dim _paragraph As New Paragraph
_paragraph.FontFamily = New FontFamily(_element.Attribute(XName.[Get]("FontFamily")).Value)
_paragraph.FontSize = Double.Parse(_element.Attribute(XName.[Get]("FontSize")).Value)
_paragraph.FontStretch = DirectCast(GetType(FontStretches).GetProperty(
_element.Attribute(XName.[Get]("FontStretch")).Value).GetValue(Nothing, Nothing), FontStretch)
_paragraph.FontStyle = DirectCast(GetType(FontStyles).GetProperty(
_element.Attribute(XName.[Get]("FontStyle")).Value).GetValue(Nothing, Nothing), FontStyle)
_paragraph.FontWeight = DirectCast(GetType(FontWeights).GetProperty(
_element.Attribute(XName.[Get]("FontWeight")).Value).GetValue(Nothing, Nothing), FontWeight)
_colour = _element.Attribute(XName.[Get]("Foreground")).Value
_colour = _colour.Remove(0, 1)
_paragraph.Foreground = New SolidColorBrush(Color.FromArgb(
Byte.Parse(_colour.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(4, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(6, 2), System.Globalization.NumberStyles.HexNumber)))
For Each _inline As XElement In _element.Descendants("Inline")
If _inline.Attribute(XName.[Get]("Type")).Value = "Run" Then
Dim _run As New Run
_run.FontFamily = New FontFamily(_element.Attribute(XName.[Get]("FontFamily")).Value)
_run.FontSize = Double.Parse(_element.Attribute(XName.[Get]("FontSize")).Value)
_run.FontStretch = DirectCast(GetType(FontStretches).GetProperty(
_element.Attribute(XName.[Get]("FontStretch")).Value).GetValue(Nothing, Nothing), FontStretch)
_run.FontStyle = DirectCast(GetType(FontStyles).GetProperty(
_element.Attribute(XName.[Get]("FontStyle")).Value).GetValue(Nothing, Nothing), FontStyle)
_run.FontWeight = DirectCast(GetType(FontWeights).GetProperty(
_element.Attribute(XName.[Get]("FontWeight")).Value).GetValue(Nothing, Nothing), FontWeight)
_colour = _element.Attribute(XName.[Get]("Foreground")).Value
_colour = _colour.Remove(0, 1)
_run.Foreground = New SolidColorBrush(Color.FromArgb(
Byte.Parse(_colour.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(4, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(6, 2), System.Globalization.NumberStyles.HexNumber)))
If _inline.Attribute(XName.[Get]("TextDecorations")).Value = "Underline" Then
_run.TextDecorations = TextDecorations.Underline
End If
_run.Text = _inline.Attribute(XName.[Get]("Text")).Value
_paragraph.Inlines.Add(_run)
End If
Next
Blocks.Add(_paragraph)
Next
End SubÉtape 13▲
Toujours dans la vue de code pour MainPage.xaml, en dessous du End Sub pour le constructeur Private Sub Read() tapez la fonction suivante :
Private Function Write(ByRef Blocks As BlockCollection) As String
Dim _write As New Text.StringBuilder
Dim _doc = From block In Blocks _
From inline In TryCast(block, Paragraph).Inlines
Where inline.GetType Is GetType(InlineUIContainer) _
Select inline
If _doc.Count = 0 Then
_write.Append("<doc>")
For Each _block As Block In Blocks
Dim _paragraph As New Paragraph
_write.Append("<Paragraph ")
_write.Append("Name='" & _paragraph.Name &"' ")
_write.Append("FontFamily='" & _paragraph.FontFamily.ToString & "' ")
_write.Append("FontSize='" & _paragraph.FontSize & "' ")
_write.Append("FontStretch='" & _paragraph.FontStretch.ToString & "' ")
_write.Append("FontStyle='" & _paragraph.FontStyle.ToString & "' ")
_write.Append("FontWeight='" & _paragraph.FontWeight.ToString & "' ")
_write.Append("Foreground='" & TryCast(_paragraph.Foreground, SolidColorBrush).Color.ToString & "'>")
For Each _inline In TryCast(_block, Paragraph).Inlines
If TypeOf _inline Is Run Then
Dim _run As Run = TryCast(_inline, Run)
_write.Append("<Inline Type='Run' ")
_write.Append("Name='" & _run.Name & "' ")
_write.Append("FontFamily='" & _run.FontFamily.ToString & "' ")
_write.Append("FontSize='" & _run.FontSize & "' ")
_write.Append("FontStretch='" & _run.FontStretch.ToString & "' ")
_write.Append("FontStyle='" & _run.FontStyle.ToString & "' ")
_write.Append("FontWeight='" & _run.FontWeight.ToString & "' ")
_write.Append("Foreground='" & TryCast(_run.Foreground, SolidColorBrush).Color.ToString & "' ")
_write.Append("Text='" & _run.Text & "' ")
_write.Append("TextDecorations='" & If(_run.TextDecorations Is Nothing, "", "Underline") & "'/>")
End If
Next
_write.Append("</Paragraph>")
Next
_write.Append("</doc>")
Return _write.ToString
Else
Return Nothing
End If
End FunctionÉtape 14▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le bouton « New » et tapez ceci dans le Sub New_Click:
If MessageBox.Show("Start a New Document?", "Rich Text Editor", _
MessageBoxButton.OKCancel) = MessageBoxResult.OK Then
Editor.Blocks.Clear()
End IfÉtape 15▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le bouton « Open... » et tapez ceci dans le SubOpen_Click :
Dim OpenDialog As New OpenFileDialog
OpenDialog.Filter = "Saved Files (*.sav)|*.sav"
If OpenDialog.ShowDialog Then
Try
If OpenDialog.File.Exists Then
Editor.Blocks.Clear()
Read(OpenDialog.File.OpenRead, Editor.Blocks)
End If
Catch ex As Exception
'Ignore Errors
End Try
End If
Étape 16▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le bouton « Save... » et tapez ceci dans le SubSave_Click:
Dim SaveDialog As New SaveFileDialog
SaveDialog.Filter = "Saved Files (*.sav)|*.sav"
If SaveDialog.ShowDialog Then
Try
Using FileStream As IO.StreamWriter = _
New IO.StreamWriter(SaveDialog.OpenFile)
FileStream.Write(Write(Editor.Blocks))
End Using
Catch ex As Exception
'Ignore Errors
End Try
End If
Étape 17▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le bouton « Print... » et tapez ceci dans le SubPrint_Click:
Dim _print As New PrintDocument
_print.DocumentName = "Rich Text Editor"
AddHandler _print.PrintPage, Sub(s As Object, args As PrintPageEventArgs)
args.PageVisual = Editor
args.HasMorePages = False
End Sub
AddHandler _print.EndPrint, Sub(s As Object, args As EndPrintEventArgs)
MessageBox.Show("Document Printed", _
"Rich Text Editor", MessageBoxButton.OK)
End Sub
_print.Print()
Editor.Focus()Étape 18▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le bouton « Bold » et tapez ceci dans le SubBold_Click:
If Editor.Selection.Text.Length > 0 Then ' Text Selected
If TypeOf Editor.Selection.GetPropertyValue(Run.FontWeightProperty) Is FontWeight _
AndAlso DirectCast(Editor.Selection.GetPropertyValue( _
Run.FontWeightProperty), FontWeight) = FontWeights.Normal Then
Editor.Selection.SetPropertyValue(Run.FontWeightProperty, FontWeights.Bold)
Else
Editor.Selection.SetPropertyValue(Run.FontWeightProperty, FontWeights.Normal)
End If
End If
Editor.Focus()Étape 19▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le bouton « Italic » et tapez ceci dans le Sub Italic_Click:
If Editor.Selection.Text.Length > 0 Then ' Text Selected
If TypeOf Editor.Selection.GetPropertyValue(Run.FontStyleProperty) Is FontStyle _
AndAlso DirectCast(Editor.Selection.GetPropertyValue( _
Run.FontStyleProperty), FontStyle) = FontStyles.Normal Then
Editor.Selection.SetPropertyValue(Run.FontStyleProperty, FontStyles.Italic)
Else
Editor.Selection.SetPropertyValue(Run.FontStyleProperty, FontStyles.Normal)
End If
End If
Editor.Focus()Étape 20▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le bouton « Underline » et tapez ceci dans le SubUnderline_Click:
If Editor.Selection.Text.Length > 0 Then ' Text Selected
If Editor.Selection.GetPropertyValue(Run.TextDecorationsProperty) Is Nothing Then
Editor.Selection.SetPropertyValue(Run.TextDecorationsProperty, TextDecorations.Underline)
Else
Editor.Selection.SetPropertyValue(Run.TextDecorationsProperty, Nothing)
End If
End If
Editor.Focus()Étape 21▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le bouton « Time Date » et tapez ceci dans le SubTimeDate_Click:
Editor.Selection.Text = Format(Now, "HH:mm dd/MM/yyyy")
Editor.Focus()
Étape 22▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le premier ComboBox(Font) ou sur celui à l'extrême gauche et tapez ceci dans le SubFont_SelectionChanged:
If Editor IsNot Nothing AndAlso Editor.Selection.Text.Length > 0 Then ' Text Selected
Editor.Selection.SetPropertyValue(Run.FontFamilyProperty, _
New FontFamily(CType(Font.SelectedItem, ComboBoxItem).Tag))
Editor.Focus()
End IfÉtape 23▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le second ComboBox(Size) et tapez ceci dans le SubSize_SelectionChanged:
If Editor IsNot Nothing AndAlso Editor.Selection.Text.Length > 0 Then ' Text Selected
Editor.Selection.SetPropertyValue(Run.FontSizeProperty, _
Double.Parse(TryCast(Size.SelectedItem, ComboBoxItem).Tag))
Editor.Focus()
End IfÉtape 24▲
Retournez au concepteur de vues en sélectionnant l'onglet MainPage.xaml, ou faites un clic droit sur la page ou sur l'entrée pour MainPage.xaml dans l'Explorateur de solutions et choisissez l'option Concepteur de vues.
Double-cliquez sur le troisième ComboBox (Colour) et tapez ceci dans le Sub Colour_SelectionChanged:
If Editor IsNot Nothing AndAlso Editor.Selection.Text.Length > 0 Then ' Text Selected
Dim _colour As String = CType(Colour.SelectedItem, ComboBoxItem).Tag
Dim _brush As New SolidColorBrush(Color.FromArgb(
Byte.Parse(_colour.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(4, 2), System.Globalization.NumberStyles.HexNumber),
Byte.Parse(_colour.Substring(6, 2), System.Globalization.NumberStyles.HexNumber)))
Editor.Selection.SetPropertyValue(Run.ForegroundProperty, _brush)
Editor.Focus()
End IfÉtape 25▲
Enregistrez le projet maintenant que vous avez terminé l'application Silverlight. Sélectionnez Debug ensuite Démarrer le débogage ou cliquez sur Démarrer le débogage :

Une fois que vous l'aurez fait, ce qui suit apparaîtra dans une nouvelle fenêtre du navigateur :

Étape 26▲
Vous pouvez saisir du texte dans le RichTextArea, et ensuite appliquer la mise en forme, les polices, les tailles et les couleurs - puis enregistrer le fichier pour l'ouvrir plus tard :

Étape 27▲
Fermez la fenêtre du navigateur en cliquant sur le bouton Fermer
en haut à droite du navigateur Web pour Arrêter l'application.
Conclusion▲
Ceci est un éditeur de texte riche très simple avec quelques-unes des fonctionnalités communes prises en charge par Silverlight. Voyez si vous pouvez ajouter davantage de fonctionnalités à cette application telles que l'alignement de texte.
Liens▲
Remerciements▲
Je tiens ici à remercier Peter Bull de m'avoir autorisé à traduire son tutoriel.
Je remercie tomlev pour sa relecture technique et ses propositions.
Je remercie également ClaudeLELOUP pour sa relecture orthographique et ses propositions.





















