Monday, December 14, 2009

Five Minute Silverlight 4 Aides-Memoire #5 – Rich Text Area Control

<RichTextArea x:Name="Editor">
    <RichTextArea.Blocks>
        <Paragraph>
            <Run Foreground="Blue" Text="This is "/>
            <Run Foreground="Red" FontWeight="Bold" Text="some sample " />
            <Run FontStyle="Italic" Text="text" />
        </Paragraph>
        <Paragraph>
            <Run Text="Here is "/>
            <Run TextDecorations="Underline" Text="some more" />
        </Paragraph>
    </RichTextArea.Blocks>
</RichTextArea>

void UnderlineSelection_Click(object sender, RoutedEventArgs e)
{
    var currentValue = this.Editor.Selection.GetPropertyValue(TextElement.TextDecorationsProperty);
    TextDecorationCollection setValue = TextDecorations.Underline;
    if (currentValue != DependencyProperty.UnsetValue)
        setValue = (TextDecorationCollection)currentValue == setValue ? null : setValue;
    this.Editor.Selection.SetPropertyValue(TextElement.TextDecorationsProperty, setValue);
}

void ItalicSelection_Click(object sender, RoutedEventArgs e)
{
    var currentValue = this.Editor.Selection.GetPropertyValue(TextElement.FontStyleProperty);
    FontStyle setValue = FontStyles.Italic;
    FontStyle defaultValue = FontStyles.Normal;
    if (currentValue != DependencyProperty.UnsetValue)
        setValue = (FontStyle)currentValue == setValue ? defaultValue : setValue;
    this.Editor.Selection.SetPropertyValue(TextElement.FontStyleProperty, setValue);
}

void BoldSelection_Click(object sender, RoutedEventArgs e)
{
    var currentValue = this.Editor.Selection.GetPropertyValue(TextElement.FontWeightProperty);
    FontWeight setValue = FontWeights.Bold;
    FontWeight defaultValue = FontWeights.Normal;
    if (currentValue != DependencyProperty.UnsetValue)
        setValue = (FontWeight)currentValue == setValue ? defaultValue : setValue;
    this.Editor.Selection.SetPropertyValue(TextElement.FontWeightProperty, setValue);
}

image

No comments: