■ 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 |
<?xml version="1.0" encoding="utf-8"?> <Page x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" FontFamily="나눔고딕코딩" FontSize="16"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="10" /> <RowDefinition Height="*" /> <RowDefinition Height="10" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" HorizontalAlignment="Left" Orientation="Horizontal"> <Button Name="openFileButton" ToolTipService.ToolTip="Open file"> <Button.Content> <FontIcon Glyph=""/> </Button.Content> </Button> <Button Name="saveFileButton" Margin="5 0 0 0" ToolTipService.ToolTip="Save file"> <Button.Content> <FontIcon Glyph=""/> </Button.Content> </Button> </StackPanel> <StackPanel Grid.Row="0" HorizontalAlignment="Right" Orientation="Horizontal"> <Button Name="boldButton" ToolTipService.ToolTip="Bold"> <Button.Content> <FontIcon Glyph=""/> </Button.Content> </Button> <Button Name="italicButton" Margin="5 0 0 0" ToolTipService.ToolTip="Italic"> <Button.Content> <FontIcon Glyph=""/> </Button.Content> </Button> <DropDownButton Name="fontColorButton" Margin="5 0 0 0" BorderThickness="0" ToolTipService.ToolTip="Font color" Background="Transparent"> <SymbolIcon Symbol="FontColor" /> <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="Margin" Value="5" /> <Setter Property="MinWidth" Value="0" /> <Setter Property="MinHeight" Value="0" /> <Setter Property="Padding" Value="0" /> </Style> </VariableSizedWrapGrid.Resources> <Button Name="redColorButton"> <Button.Content> <Rectangle Fill="Red" /> </Button.Content> </Button> <Button Name="orangeColorButton"> <Button.Content> <Rectangle Fill="Orange" /> </Button.Content> </Button> <Button Name="yellowColorButton"> <Button.Content> <Rectangle Fill="Yellow" /> </Button.Content> </Button> <Button Name="greenColorButton"> <Button.Content> <Rectangle Fill="Green" /> </Button.Content> </Button> <Button Name="blueColorButton"> <Button.Content> <Rectangle Fill="Blue" /> </Button.Content> </Button> <Button Name="indigoColorButton"> <Button.Content> <Rectangle Fill="Indigo" /> </Button.Content> </Button> <Button Name="violetColorButton"> <Button.Content> <Rectangle Fill="Violet" /> </Button.Content> </Button> <Button Name="grayColorButton"> <Button.Content> <Rectangle Fill="Gray" /> </Button.Content> </Button> </VariableSizedWrapGrid> </Flyout> </DropDownButton.Flyout> </DropDownButton> </StackPanel> <RichEditBox Name="richEditBox" Grid.Row="2" /> <StackPanel Name="findStackPanel" Grid.Row="4" Orientation="Horizontal"> <TextBlock VerticalAlignment="Center" Text="Find" /> <TextBox Name="findTextBox" Margin="10 0 0 0" Width="150" PlaceholderText="Enter search text" GotFocus="{x:Bind SetFindTextBoxHighlight}" TextChanged="{x:Bind SetFindTextBoxHighlight}" LostFocus="{x:Bind ClearFindTextBoxHighlight}" /> </StackPanel> </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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Windows.Storage; using Windows.Storage.Pickers; using Windows.Storage.Provider; using Windows.Storage.Streams; using Windows.UI; using Windows.UI.Popups; using WinRT.Interop; using Microsoft.UI; using Microsoft.UI.Text; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Shapes; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public sealed partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 활성 윈도우 구하기 - GetActiveWindow() /// <summary> /// 활성 윈도우 구하기 /// </summary> /// <returns></returns> [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Auto, PreserveSig = true, SetLastError = false)] private static extern IntPtr GetActiveWindow(); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 현재 색상 /// </summary> private Color currentColor = Colors.Green; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.openFileButton.Click += openFileButton_Click; this.saveFileButton.Click += saveFileButton_Click; this.boldButton.Click += boldButton_Click; this.italicButton.Click += italicButton_Click; this.redColorButton.Click += colorButton_Click; this.orangeColorButton.Click += colorButton_Click; this.yellowColorButton.Click += colorButton_Click; this.greenColorButton.Click += colorButton_Click; this.blueColorButton.Click += colorButton_Click; this.indigoColorButton.Click += colorButton_Click; this.violetColorButton.Click += colorButton_Click; this.grayColorButton.Click += colorButton_Click; this.richEditBox.GotFocus += richEditBox_GotFocus; this.richEditBox.TextChanged += richEditBox_TextChanged; this.richEditBox.Document.GetDefaultCharacterFormat().ForegroundColor = Colors.Green; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region Open file 버튼 클릭시 처리하기 - openFileButton_Click(sender, e) /// <summary> /// Open file 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void openFileButton_Click(object sender, RoutedEventArgs e) { FileOpenPicker fileOpenPicker = new FileOpenPicker(); fileOpenPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; fileOpenPicker.FileTypeFilter.Add(".rtf"); if(Window.Current == null) { IntPtr windowHandle = GetActiveWindow(); InitializeWithWindow.Initialize(fileOpenPicker, windowHandle); } 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 Save file 버튼 클릭시 처리하기 - saveFileButton_Click(sender, e) /// <summary> /// Save file 버튼 클릭시 처리하기 /// </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"; if(Window.Current == null) { IntPtr windowHandle = GetActiveWindow(); InitializeWithWindow.Initialize(fileSavePicker, windowHandle); } 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("File " + storageFile.Name + " couldn't be saved."); await messageDialog.ShowAsync(); } } } #endregion #region Bold 버튼 클릭시 처리하기 - boldButton_Click(sender, e) /// <summary> /// Bold 버튼 클릭시 처리하기 /// </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 Italic 버튼 클릭시 처리하기 - italicButton_Click(sender, e) /// <summary> /// Italic 버튼 클릭시 처리하기 /// </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 색상 버튼 클릭시 처리하기 - colorButton_Click(sender, e) /// <summary> /// 색상 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void colorButton_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; this.fontColorButton.Flyout.Hide(); this.richEditBox.Focus(FocusState.Keyboard); this.currentColor = color; } #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 _); ITextRange textRange = 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 Find 텍스트 박스 하이라이트 설정하기 - SetFindTextBoxHighlight() /// <summary> /// Find 텍스트 박스 하이라이트 설정하기 /// </summary> private void SetFindTextBoxHighlight() { ClearFindTextBoxHighlight(); 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 Find 텍스트 박스 하이라이트 지우기 - ClearFindTextBoxHighlight() /// <summary> /// Find 텍스트 박스 하이라이트 지우기 /// </summary> private void ClearFindTextBoxHighlight() { 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 } } |