// This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT. // Copyright (C) Leszek Pomianowski and WPF UI Contributors. // All Rights Reserved. using System; using System.Diagnostics; using System.Windows; using WPFluent.Appearance; using WPFluent.Input; using Color = System.Windows.Media.Color; namespace WPFluent.Controls; /// /// Formats and display a fragment of the source code. /// public class CodeBlock : System.Windows.Controls.ContentControl { private string _sourceCode = string.Empty; /// /// Property for . /// public static readonly DependencyProperty SyntaxContentProperty = DependencyProperty.Register( nameof(SyntaxContent), typeof(object), typeof(CodeBlock), new PropertyMetadata(null) ); /// /// Property for . /// public static readonly DependencyProperty ButtonCommandProperty = DependencyProperty.Register( nameof(ButtonCommand), typeof(IRelayCommand), typeof(CodeBlock) ); /// /// Gets the formatted . /// public object? SyntaxContent { get => GetValue(SyntaxContentProperty); internal set => SetValue(SyntaxContentProperty, value); } /// /// Gets the command triggered after clicking the control button. /// internal IRelayCommand ButtonCommand => (IRelayCommand)GetValue(ButtonCommandProperty); /// /// Initializes a new instance of the class, and assigns default action. /// public CodeBlock() { SetValue(ButtonCommandProperty, new RelayCommand(OnTemplateButtonClick)); ApplicationThemeManager.Changed += ThemeOnChanged; } private void ThemeOnChanged(ApplicationTheme currentApplicationTheme, Color systemAccent) { UpdateSyntax(); } /// /// This method is invoked when the Content property changes. /// /// The old value of the Content property. /// The new value of the Content property. protected override void OnContentChanged(object oldContent, object newContent) { UpdateSyntax(); } protected virtual void UpdateSyntax() { _sourceCode = Highlighter.Clean(Content as string ?? string.Empty); var richTextBox = new RichTextBox() { IsTextSelectionEnabled = true, VerticalContentAlignment = VerticalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, HorizontalContentAlignment = HorizontalAlignment.Left, }; richTextBox.Document.Blocks.Clear(); richTextBox.Document.Blocks.Add(Highlighter.FormatAsParagraph(_sourceCode)); SetCurrentValue(SyntaxContentProperty, richTextBox); } private void OnTemplateButtonClick(string? _) { Debug.WriteLine($"INFO | CodeBlock source: \n{_sourceCode}", "Wpf.Ui.CodeBlock"); try { Clipboard.Clear(); Clipboard.SetText(_sourceCode); } catch (Exception e) { Debug.WriteLine(e); } } }