Let's say I have RichTextBox from the Windows WPF library, and I'm trying to make it so I can select text in the richtextbox and click a bold button. as soon as I click the bold button the selected text should remain except what's in the section turns bold, and when i click the bold button again the bold should disappear and the selection should remain unchanged.
Now for what I observe, I click block and the selection disappears. Here's my code to show tht:
<Window x:Class="WpfApp2.MainWindow"
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:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<DockPanel>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
<Button Name="Bold" Content="Bold" Click="Bold_Click"/>
</StackPanel>
<RichTextBox Name="RichTextBox1" />
</DockPanel>
</Window>
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace WpfApp2 {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
RichTextBox1.CaretPosition.InsertTextInRun("Select this text with a mouse click-and-drag, "
+ "then click bold button, and observe that "
+ "selection highlight disappears");
}
private bool SelectionIsBold() {
var weight = RichTextBox1.Selection.GetPropertyValue(FontWeightProperty);
var unset = DependencyProperty.UnsetValue;
var SelectionIsBold = weight != unset && (FontWeight)weight == FontWeights.Bold;
return SelectionIsBold;
}
private void Bold_Click(object sender, RoutedEventArgs e) {
if (RichTextBox1.Selection.IsEmpty) return;
var textRange = RichTextBox1.Selection;
var len = RichTextBox1.Selection.Text.Length;
var startpos = RichTextBox1.CaretPosition.GetPositionAtOffset(0);
var endpos = RichTextBox1.CaretPosition.GetPositionAtOffset(len); //GetPoint(start, len);
if (SelectionIsBold())
RichTextBox1.Selection.ApplyPropertyValue(Inline.FontWeightProperty, FontWeights.Normal);
else
RichTextBox1.Selection.ApplyPropertyValue(Inline.FontWeightProperty, FontWeights.Bold);
// ==>> DOESN"T WORK: Attempt to Reselect Text After ApplyPropertyValue because it unhighlights the selection...
RichTextBox1.SelectionBrush = new SolidColorBrush(Colors.Red);
RichTextBox1.Selection.Select(startpos, endpos);
}
} // class
} // namespace