■ RichEditBox 엘리먼트에서 커스텀 에디터를 사용하는 방법을 보여준다.
▶ MainPage.xaml
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
<Page x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:muxc="using:Microsoft.UI.Xaml.Controls" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" FontFamily="나눔고딕코딩" FontSize="16"> <Grid> <RelativePanel Margin="100" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <RelativePanel.Resources> <ResourceDictionary> <Style TargetType="Button"> <Setter Property="BorderThickness" Value="0" /> <Setter Property="Margin" Value="0 0 10 0" /> <Setter Property="Background" Value="Transparent" /> </Style> <ResourceDictionary.ThemeDictionaries> <ResourceDictionary x:Key="HighContrast"> <StaticResource x:Key="ButtonBackgroundPointerOver" ResourceKey="SystemColorHighlightColor" /> </ResourceDictionary> </ResourceDictionary.ThemeDictionaries> </ResourceDictionary> </RelativePanel.Resources> <Button Name="openFileButton" ToolTipService.ToolTip="파일 열기" Click="openFileButton_Click"> <Button.Content> <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" /> </Button.Content> </Button> <Button RelativePanel.RightOf="openFileButton" ToolTipService.ToolTip="파일 저장하기" Click="saveFileButton_Click"> <Button.Content> <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" /> </Button.Content> </Button> <muxc:DropDownButton Name="fontColorButton" RelativePanel.AlignRightWithPanel="True" BorderThickness="0" Background="Transparent" ToolTipService.ToolTip="폰트 색상"> <SymbolIcon Symbol="FontColor" /> <muxc:DropDownButton.Flyout> <Flyout Placement="Bottom"> <VariableSizedWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="3"> <VariableSizedWrapGrid.Resources> <Style TargetType="Rectangle"> <Setter Property="Width" Value="32" /> <Setter Property="Height" Value="32" /> </Style> <Style TargetType="Button"> <Setter Property="Padding" Value="0" /> <Setter Property="MinWidth" Value="0" /> <Setter Property="MinHeight" Value="0" /> <Setter Property="Margin" Value="5" /> </Style> </VariableSizedWrapGrid.Resources> <Button Click="fontColorButton_Click"> <Button.Content> <Rectangle Fill="Red" /> </Button.Content> </Button> <Button Click="fontColorButton_Click"> <Button.Content> <Rectangle Fill="Orange" /> </Button.Content> </Button> <Button Click="fontColorButton_Click"> <Button.Content> <Rectangle Fill="Yellow" /> </Button.Content> </Button> <Button Click="fontColorButton_Click"> <Button.Content> <Rectangle Fill="Green" /> </Button.Content> </Button> <Button Click="fontColorButton_Click"> <Button.Content> <Rectangle Fill="Blue" /> </Button.Content> </Button> <Button Click="fontColorButton_Click"> <Button.Content> <Rectangle Fill="Indigo" /> </Button.Content> </Button> <Button Click="fontColorButton_Click"> <Button.Content> <Rectangle Fill="Violet" /> </Button.Content> </Button> <Button Click="fontColorButton_Click"> <Button.Content> <Rectangle Fill="Gray" /> </Button.Content> </Button> </VariableSizedWrapGrid> </Flyout> </muxc:DropDownButton.Flyout> </muxc:DropDownButton> <Button Name="italicButton" RelativePanel.LeftOf="fontColorButton" Click="italicButton_Click" ToolTipService.ToolTip="Italic"> <Button.Content> <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" /> </Button.Content> </Button> <Button RelativePanel.LeftOf="italicButton" ToolTipService.ToolTip="Bold" Click="boldButton_Click"> <Button.Content> <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" /> </Button.Content> </Button> <RichEditBox Name="richEditBox" RelativePanel.Below="openFileButton" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True" MinWidth="300" Height="300" GotFocus="richEditBox_GotFocus" TextChanged="richEditBox_TextChanged" /> <StackPanel RelativePanel.Below="richEditBox" RelativePanel.AlignLeftWith="richEditBox" Margin="0 10 0 0" Orientation="Horizontal"> <TextBlock VerticalAlignment="Center" Margin="0 0 0 3" Text="검색 문자열 :" /> <TextBox Name="findTextBox" Margin="10 0 0 0" Width="300" PlaceholderText="검색할 텍스트를 입력해 주시기 바립니다." TextChanged="{x:Bind SetHighlight}" GotFocus="{x:Bind SetHighlight}" LostFocus="{x:Bind RemoveHighlight}" /> </StackPanel> </RelativePanel> </Grid> </Page> |
▶ MainPage.xaml.cs
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
using System; using System.Collections.Generic; using Windows.Foundation; using Windows.Graphics.Display; using Windows.Storage; using Windows.Storage.Pickers; using Windows.Storage.Provider; using Windows.Storage.Streams; using Windows.UI; using Windows.UI.Popups; using Windows.UI.Text; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Shapes; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public sealed partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 현재 색상 /// </summary> private Color currentColor = Colors.Green; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); #region 윈도우 크기를 설정한다. double width = 800d; double height = 600d; double dpi = (double)DisplayInformation.GetForCurrentView().LogicalDpi; ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize; Size windowSize = new Size(width * 96d / dpi, height * 96d / dpi); ApplicationView.PreferredLaunchViewSize = windowSize; Window.Current.Activate(); ApplicationView.GetForCurrentView().TryResizeView(windowSize); #endregion #region 윈도우 제목을 설정한다. ApplicationView.GetForCurrentView().Title = "RichEditBox 엘리먼트 : 커스텀 에디터 사용하기"; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 파일 열기 버튼 클릭시 처리하기 - openFileButton_Click(sender, e) /// <summary> /// 파일 열기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void openFileButton_Click(object sender, RoutedEventArgs e) { FileOpenPicker fileOpenPicker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; fileOpenPicker.FileTypeFilter.Add(".rtf"); StorageFile storageFile = await fileOpenPicker.PickSingleFileAsync(); if(storageFile != null) { using(IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read)) { this.richEditBox.Document.LoadFromStream(TextSetOptions.FormatRtf, stream); } } } #endregion #region 파일 저장 버튼 클릭시 처리하기 - saveFileButton_Click(sender, e) /// <summary> /// 파일 저장 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void saveFileButton_Click(object sender, RoutedEventArgs e) { FileSavePicker fileSavePicker = new FileSavePicker { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; fileSavePicker.FileTypeChoices.Add("Rich Text", new List<string>() { ".rtf" }); fileSavePicker.SuggestedFileName = "New Document"; StorageFile storageFile = await fileSavePicker.PickSaveFileAsync(); if(storageFile != null) { CachedFileManager.DeferUpdates(storageFile); using(IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { this.richEditBox.Document.SaveToStream(TextGetOptions.FormatRtf, stream); } FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(storageFile); if(status != FileUpdateStatus.Complete) { MessageDialog messageDialog = new MessageDialog($"{storageFile.Name} 파일을 저장할 수 없습니다."); await messageDialog.ShowAsync(); } } } #endregion #region 폰트 색상 버튼 클릭시 처리하기 - fontColorButton_Click(sender, e) /// <summary> /// 폰트 색상 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void fontColorButton_Click(object sender, RoutedEventArgs e) { Button button = sender as Button; Rectangle rectangle = button.Content as Rectangle; Color color = (rectangle.Fill as SolidColorBrush).Color; this.richEditBox.Document.Selection.CharacterFormat.ForegroundColor = color; fontColorButton.Flyout.Hide(); this.richEditBox.Focus(FocusState.Keyboard); this.currentColor = color; } #endregion #region 이탤릭체 버튼 클릭시 처리하기 - italicButton_Click(sender, e) /// <summary> /// 이탤릭체 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void italicButton_Click(object sender, RoutedEventArgs e) { this.richEditBox.Document.Selection.CharacterFormat.Italic = FormatEffect.Toggle; } #endregion #region 볼드체 버튼 클릭시 처리하기 - boldButton_Click(sender, e) /// <summary> /// 볼드체 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void boldButton_Click(object sender, RoutedEventArgs e) { this.richEditBox.Document.Selection.CharacterFormat.Bold = FormatEffect.Toggle; } #endregion #region 리치 편집 박스 포커스 획득시 처리하기 - richEditBox_GotFocus(sender, e) /// <summary> /// 리치 편집 박스 포커스 획득시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void richEditBox_GotFocus(object sender, RoutedEventArgs e) { this.richEditBox.Document.GetText(TextGetOptions.UseCrlf, out string currentRawText); ITextRange textRange = this.richEditBox.Document.GetRange(0, TextConstants.MaxUnitCount); SolidColorBrush backgroundBrush = App.Current.Resources["TextControlBackgroundFocused"] as SolidColorBrush; if(backgroundBrush != null) { textRange.CharacterFormat.BackgroundColor = backgroundBrush.Color; } } #endregion #region 리치 편집 박스 텍스트 변경시 처리하기 - richEditBox_TextChanged(sender, e) /// <summary> /// 리치 편집 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void richEditBox_TextChanged(object sender, RoutedEventArgs e) { if(this.richEditBox.Document.Selection.CharacterFormat.ForegroundColor != this.currentColor) { this.richEditBox.Document.Selection.CharacterFormat.ForegroundColor = this.currentColor; } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 하이라이트 설정하기 - SetHighlight() /// <summary> /// 하이라이트 설정하기 /// </summary> private void SetHighlight() { RemoveHighlight(); Color highlightBackgroundColor = (Color)App.Current.Resources["SystemColorHighlightColor" ]; Color highlightForegroundColor = (Color)App.Current.Resources["SystemColorHighlightTextColor"]; string textToFind = this.findTextBox.Text; if(textToFind != null) { ITextRange textRange = this.richEditBox.Document.GetRange(0, 0); while(textRange.FindText(textToFind, TextConstants.MaxUnitCount, FindOptions.None) > 0) { textRange.CharacterFormat.BackgroundColor = highlightBackgroundColor; textRange.CharacterFormat.ForegroundColor = highlightForegroundColor; } } } #endregion #region 하이라이트 제거하기 - RemoveHighlight() /// <summary> /// 하이라이트 제거하기 /// </summary> private void RemoveHighlight() { ITextRange textRange = this.richEditBox.Document.GetRange(0, TextConstants.MaxUnitCount); SolidColorBrush defaultBackgroundBrush = this.richEditBox.Background as SolidColorBrush; SolidColorBrush defaultForegroundbrush = this.richEditBox.Foreground as SolidColorBrush; textRange.CharacterFormat.BackgroundColor = defaultBackgroundBrush.Color; textRange.CharacterFormat.ForegroundColor = defaultForegroundbrush.Color; } #endregion } } |