C#/WPF

WPF FontDialog 사용하기

기공이 2016. 4. 19. 19:48

이번에 폰트를 관련하여 찾아보다 보니, WPF에서는 FontDialog가 없다고 합니다. 그래서 외국 개발자분께서 따로 만들어 주신게 있고(여기), 아니면 WinForm의 FontDialog를 사용해야 합니다.


WPF에서 FontDialog를 사용하려면 우선 참조가 필요합니다


※참조 추가 -> 어셈블리 -> System.Drawing , System.Windows.Forms 

이 두가지가 필요합니다.


System.Windows.Forms와 WPF에서 겹치는 것들은 따로 표시를 해주시기 바랍니다.


먼저 FontDialog로 font를 받아오는 것입니다.


System.Drawing.Font memFont;

System.Drawing.Color memColor;


1
2
3
4
5
6
7
8
9
10
11
12
private void btnFont_Click(object sender, RoutedEventArgs e)
{
    System.Windows.Forms.FontDialog font = new System.Windows.Forms.FontDialog();
 
    font.ShowColor = true;
 
    if (font.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        memFont = font.Font;
        memColor = font.Color;
    }
}
cs



그리고 해당 폰트를 WPF의 TextBox에 적용시키는 것입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private void ApplyFont(TextBox box)
{
    // 색 적용
    box.Foreground = new SolidColorBrush(Color.FromArgb(255, memColor.R, memColor.G, memColor.B));
 
    // 폰트 적용
    box.FontFamily = new FontFamily(memFont.Name);
 
    // 글자 크기 적용
    box.FontSize = memFont.Size;
 
    // 취소선 적용
    if (memFont.Strikeout)
    {
        box.TextDecorations.Add(new TextDecoration(TextDecorationLocation.Strikethrough,
            null, 0, TextDecorationUnit.FontRecommended, TextDecorationUnit.FontRecommended));
    }
 
    // 밑줄 적용
    if (memFont.Underline)
    {
        box.TextDecorations.Add(new TextDecoration(TextDecorationLocation.Underline,
            null, 0, TextDecorationUnit.FontRecommended, TextDecorationUnit.FontRecommended));
    }
 
    // 이탤릭체 적용
    if (memFont.Italic)
        box.FontStyle = FontStyles.Italic;
    else
        box.FontStyle = FontStyles.Normal;
 
    // 볼드체 적용
    if (memFont.Bold)
        box.FontWeight = FontWeights.Bold;
    else
        box.FontWeight = FontWeights.Normal;
}
 
cs


TextBox대신 TextBlock에도 적용이 가능하며, 

Label에는 TextDecorations가 없기 때문에 취소선과 밑줄의 적용이 불가한 것 같습니다.