2010. 1. 7. 09:00

1.RichTextArea Part 1
2.RichTextArea Part 2
3.Accessing Web Camera and Microphone
4.Right Click Mouse Events
5.MouseWheel API

6.Using Silveright Controls As Drop Targets
7.DataGrid Enhancements
8.Printing API Basics 
9.Hosting HTML Content
10.Accessing the Global Clipboard Programmatically 
11.Using the ViewBox Control 
12.Asynchronous Data Validation 
13.BiDi and Right-to-Left Support 
14.Notification API
15.Local File Access 
16.RIA Services support in Visual Studio 2010  
 

블로그 이미지 김영욱 차장 Microsoft Korea  .NET Evangelist
Enterprise UX 를 위한  UI 기술과 SOA, Cloud Computing, NUI등 다양한 분야의 접목과 응용을 통해 최적의 IT 인프라 구축을 위해서 노력하고 있다.
Email: iwinkey@hotmail.com
Blog: http://winkey.tistory.com


RichTextArea 를 설명하는 두 번째 시간입니다. 지난 강좌에서는 RichTextArea를 활용하는 기본적인 방법을 설명했습니다. 이번 강좌에서는 조금 더 진도를 나가 보도록 하겠습니다.

아래 화면은 이번 강좌의 결과물로서 얻어지는 샘플입니다.  RichTextArea안에서 다양한 형태(크기, 폰트, 속성)을 가진 문단들이 한꺼번에 사용되었으며 원하는 부분만 선택해서 속성을 변경할 수 있게 되어 있습니다. 또 RichTextArea 안에 버튼을 삽입해서 동작 시키는 것도 가능하다는 것을 볼 수 있는 샘플입니다.

 

 

먼저 RichTextArea를 구성하는 방법에 대해서 설명해 드립니다. RichTextArea안에서 내용을 표현하기 위해서 사용하는 Paragraph을 사용해야 한다. Paragraph는 RichTextArea안의 내용을 표현하기 위해서 제공되는 객체이다.

 

<Paragraph x:Name="H1"
                       FontFamily="Georgia"
                       FontSize="36"
                       FontWeight="Bold"
                       TextAlignment="Center"
                       TextDecorations="Underline">
                <LineBreak />
                Rich Text Demonstration
                <LineBreak />
</Paragraph>

위의 내용은 H1이라고 명명된 문단에 Georgia  폰트 36pt 볼드체에 가운데 정렬과 언더라인 속성을 지정했습니다. 위의 그림에서 Rich Text Demonstration라고 표시된 헤더 부분을 나타내고 있는 문단을 Paragraph로 표현한 것입니다. 중간에 LineBreak는 이름 그대로 한 줄 내려가는 Line Break 입니다.

 

또 다른 형태로 사용되는 Paragraph 형태를 보면 다음과 같습니다.

<Paragraph x:Name="p3"
                       TextAlignment="Left"
                       FontFamily="Georgia"
                       FontSize="18">
                <Run Text="This is another paragraph. Oh look, a button: " />
                <InlineUIContainer>
                    <Button x:Name="inLineButton"
                            Background="Green"
                            Content="Change line 4!"
                            FontFamily="Georgia"
                            FontSize="14"
                            Height="30"
                            Width="Auto" />
                </InlineUIContainer>
                <LineBreak />
                You can click the button or
                <Run Text=" " />
                <Hyperlink NavigateUri="http://silverlightGeek.me"
                           TargetName="">this link</Hyperlink>
</Paragraph>

Paragraph 안에서 사용되는 Run은 문단 안에서 문장의 요소를 표현하기 위해서 사용되는 것으로 BreakLine과 같은 종류로 볼 수 있습니다. 또 재미있는 것은 InlineUIContainer 객체인데 이 객체를 통해서 각종 UI Control을 RichTextArea안에 포함시킬 수 있다. 위의 소스에서는 버튼을 삽입 한 것을 볼 수 있습니다.

마지막에 포함되어 있는 Hyperlink 객체는 링크를 표현하기 위해서 사용했습니다.

 

전체 XAML코드는 다음과 같습니다.

<UserControl x:Class="RTA.MainPage"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:doc="clr-namespace:System.Windows.Documents;assembly=System.Windows"
             mc:Ignorable="d"
             d:DesignHeight="500"
             d:DesignWidth="600">

    <Grid x:Name="LayoutRoot"
          Background="White"> 
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="5*" />
        </Grid.RowDefinitions>
        <StackPanel Name="stackPanel1"
                    HorizontalAlignment="Stretch"
                    Margin="0"
                    VerticalAlignment="Stretch"
                    Orientation="Horizontal">
            <CheckBox  Name="IsReadOnly"
                       Content="ReadOnly"
                       FontFamily="Georgia"
                       FontSize="14"
                       VerticalAlignment="Bottom"
                       HorizontalAlignment="Left"
                       Height="20"
                       Width="Auto"
                       Margin="5"
                       IsChecked="False" />
            <Button x:Name="Bold"
                    Content="Bold"
                    FontFamily="Georgia"
                    FontSize="14"
                    Margin="5"
                    VerticalAlignment="Bottom"
                    HorizontalAlignment="Left"
                    Height="Auto"
                    Width="60" />
        </StackPanel>
        <RichTextArea x:Name="rta"
                      Grid.Row="1" 
                      HorizontalAlignment="Stretch"
                      VerticalAlignment="Stretch"
                      TextWrapping="Wrap"
                      IsReadOnly="False">

            <Paragraph x:Name="H1"
                       FontFamily="Georgia"
                       FontSize="36"
                       FontWeight="Bold"
                       TextAlignment="Center"
                       TextDecorations="Underline">
                <LineBreak />
                Rich Text Demonstration
                <LineBreak />
            </Paragraph>
            <Paragraph x:Name="P1"
                       FontFamily="Georgia"
                       FontSize="14"
                       TextAlignment="Left">
                The text in this first paragraph is left aligned, Georgia 14.
            </Paragraph>
            <Paragraph x:Name="P2"
                       FontFamily="Georgia"
                       FontSize="12" 
                       TextAlignment="Right">
                <LineBreak />
                This is line one of the second paragraph (right aligned)
                <LineBreak />
                This is line two of the second paragraph
                <LineBreak />
                <Italic>
                    This is line three and it is in italic
                </Italic>
                <LineBreak />
                <Run x:Name="run1"
                     Text="This is line four and it is in a run!" />
                <LineBreak />
            </Paragraph>
            <Paragraph x:Name="p3"
                       TextAlignment="Left"
                       FontFamily="Georgia"
                       FontSize="18">
                <Run Text="This is another paragraph. Oh look, a button: " />
                <InlineUIContainer>
                    <Button x:Name="inLineButton"
                            Background="Green"
                            Content="Change line 4!"
                            FontFamily="Georgia"
                            FontSize="14"
                            Height="30"
                            Width="Auto" /> 
                </InlineUIContainer>
                <LineBreak />
                You can click the button or
                <Run Text=" " />
                <Hyperlink NavigateUri="http://silverlightGeek.me"
                           TargetName="">this link</Hyperlink>
            </Paragraph>

        </RichTextArea>
    </Grid>
</UserControl>

 

UI가 완성되었으니 C# 코드를 추가할 차례 입니다.  MainPage() 안에서 Loaded 이벤트 핸들러를 작성합니다.

public MainPage()
{
    InitializeComponent();
    Loaded += new RoutedEventHandler(MainPage_Loaded);
}

 

Loaded 이벤트 핸들러에서 UI과 관련된 초기화 작업과 추가적인 이벤트 핸들러를 작성해 봅니다.

 

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
   rta.IsReadOnly = false;
   Bold.Click += new RoutedEventHandler( Bold_Click );
   IsReadOnly.Click += new RoutedEventHandler( IsReadOnly_Click );
   inLineButton.Click += new RoutedEventHandler( inLineButton_Click );
}

 

먼저 rta.IsReadOnly = false를 통해서 RichTextArea를 쓰기 가능한 상태로 만들어 놓습니다. 그리고 Bold 속성을 추가하는 버튼과 ReadOnly 상태로 전환할 체크박스 그리고 RichTextArea 안에 추가해 두었던 버튼 등의 이벤트 핸들러를 설정합니다.

 

void inLineButton_Click( object sender, RoutedEventArgs e )
{
   run1.Text = "Whoa! I just changed this text dynamically!";
   run1.FontSize = 18;
   run1.FontWeight = FontWeights.Bold;
}

 

RichTextArea안에 추가 되어 있는 inLineButton에 대한 이벤트 핸들러에서는 Run 객체인 run1의 Text를 변경하고 FontSize와 Bold 속성을 변경할 수 있는 코드가 추가 되어 있다.

 

마지막으로 RichTextArea 안에서 선택한 영역을 Bold 속성으로 변경해 주는 기능을 추가 해 봅니다.

 

void Bold_Click( object sender, RoutedEventArgs e )
{
   if ( !string.IsNullOrEmpty( rta.Selection.Text ) )
   {
      rta.Selection.SetPropertyValue(
         TextElement.FontWeightProperty, FontWeights.Bold );
   }
}

 

string.IsNullOrEmpty( )를 사용해서 선택한 영역이 없을 경우를 먼저 체크하고 선택된 영역이 있을 경우에 Selection.SetPropertyValue( )를 사용해서 원하는 속성으로 변경하는 것을 볼 수 있습니다.

 

전체 소스는 첨부 된 소스 파일을 참조하시기 바랍니다. ^^