Настройка стиля шрифта для RichTextBox в vb.net - PullRequest
3 голосов
/ 23 декабря 2011

У меня проблемы с настройкой стиля шрифта в RichTextBox, и я видел несколько разных подходов, которые говорят об отдельных атрибутах (например, включение и выключение жирным шрифтом) ... но я пытаюсь сделать так Мой класс шрифта может настроить любой атрибут (жирный, курсив, подчеркивание).

Я понимаю, что Font.Style - это набор логических флагов (битовое поле?) ... но я не уверен, как обрабатывать атрибуты одновременно.

Вот неприятный код:

Public Sub ModifyFontStyle(Optional ByVal Plain As Object = Nothing, Optional ByVal Bold As Object = Nothing, _
                           Optional ByVal Italics As Object = Nothing, Optional ByVal Underlined As Object = Nothing)
    Dim newFontStyle As System.Drawing.FontStyle


    If Plain Then
        newFontStyle = Drawing.FontStyle.Regular
        GivenFont = New Drawing.Font(GivenFont.FontFamily, GivenFont.Size, newFontStyle)
        Exit Sub
    End If

    If Bold IsNot Nothing Then
        If Bold Then
            newFontStyle = GivenFont.Style + Drawing.FontStyle.Bold
        Else
            newFontStyle = GivenFont.Style - Drawing.FontStyle.Bold
        End If
    End If


    If Italics IsNot Nothing Then
        If Italics Then
            newFontStyle = GivenFont.Style + Drawing.FontStyle.Italic
        Else
            newFontStyle = GivenFont.Style - Drawing.FontStyle.Italic
        End If
    End If

    If Underlined IsNot Nothing Then
        If Underlined Then
            newFontStyle = GivenFont.Style + Drawing.FontStyle.Underline
        Else
            newFontStyle = GivenFont.Style - Drawing.FontStyle.Underline
        End If
    End If

    GivenFont = New Drawing.Font(GivenFont.FontFamily, GivenFont.Size, newFontStyle)

End Sub

А вот возможная проблема с этим кодом:

  • Я переключаю жирный шрифт (на true) - текст выделяется жирным шрифтом.
  • Я переключаю подчеркивание - текст теперь выделен жирным шрифтом и подчеркнут.
  • Я переключаю курсив - текст теперь выделен жирным шрифтом, подчеркнут и выделен курсивом.
  • Я снова переключаю жирный шрифт (на false) - текст зачеркнут.

Что происходит со шрифтом? Текст должен быть подчеркнут и курсивом не зачеркнут ...

Это логическая ошибка или простое недоразумение с моей стороны?

Что ж, спасибо за ваше время, я буду с ним возиться, пока он не заработает, или я получу ответ, который работает,

Ответы [ 2 ]

3 голосов
/ 23 декабря 2011

Вы используете неправильные операторы. Они действительно похожи на битовые флаги, перечисление имеет атрибут [Flags]. Вам нужно будет использовать оператор Or, чтобы включить стиль, и оператор And, чтобы отключить стиль. Как это:

    Dim style = Me.Font.Style
    '--- turn bold on
    style = style Or FontStyle.Bold
    '--- turn bold off
    style = style And Not FontStyle.Bold
0 голосов
/ 24 декабря 2011

Ну, я понял. Я заставил его работать успешно.

Public Sub ModifyFontStyle(Optional ByVal Plain As Object = Nothing, Optional ByVal Bold As Object = Nothing, _
                           Optional ByVal Italics As Object = Nothing, Optional ByVal Underlined As Object = Nothing)
    Dim newFontStyle As System.Drawing.FontStyle


    If Plain Then
        newFontStyle = Drawing.FontStyle.Regular
        GivenFont = New Drawing.Font(GivenFont.FontFamily, GivenFont.Size, newFontStyle)
        Exit Sub
    End If

    If Bold IsNot Nothing Then
        If Bold And Not GivenFont.Bold Then
            newFontStyle = GivenFont.Style + Drawing.FontStyle.Bold
        Else
            newFontStyle = GivenFont.Style - Drawing.FontStyle.Bold
        End If
    End If


    If Italics IsNot Nothing Then
        If Italics And Not GivenFont.Italic Then
            newFontStyle = GivenFont.Style + Drawing.FontStyle.Italic
        Else
            newFontStyle = GivenFont.Style - Drawing.FontStyle.Italic
        End If
    End If

    If Underlined IsNot Nothing Then
        If Underlined And Not GivenFont.Underline Then
            newFontStyle = GivenFont.Style + Drawing.FontStyle.Underline
        Else
            newFontStyle = GivenFont.Style - Drawing.FontStyle.Underline
        End If
    End If

    GivenFont = New Drawing.Font(GivenFont.FontFamily, GivenFont.Size, newFontStyle)

End Sub

Спасибо за ваше время!

...