2009年7月16日星期四

RichTextBox highlight the ToggleBold button automatically

Yesterday, I meet a requirement that how to highlight the ToggleBold Button Automatically, like Office Word, when the selected text in the RichTextBox is in bold font, the ToggleBold Button in the toolbar will be highlighted. On the other hand, the ToggleBold Button will remove the highlighted color when the selected text in not in bold or the selected text in bold and non-bold mixture.


At the first glance, it seems rather easy. but it took me several hours to make it work. At first, I want to accomplish this functionaility with only XAML code, however, I found there were some difficulities. So I decided to use some additonal procedure code.


The following is the XAML code:

<Window x:Class="RichTextBoxBoldHighlight.Window1"   x:Name="window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RichTextBoxBoldHighlight"
Title="Window1" Height="300" Width="300"

>
<
Grid>
<
DockPanel>
<
ToolBar DockPanel.Dock="Top">
<
Button Name="ToggleBold" Click="ToggleBold_Click"
Tag="{Binding ElementName=window1, Path= FWeight}"
>
B
<Button.Style>
<
Style TargetType="{x:Type Button}">
<
Style.Triggers>
<
Trigger Property="Tag" Value="Bold">
<
Setter Property="Background" Value="CadetBlue"></Setter>
</
Trigger>
</
Style.Triggers>
</
Style>
</
Button.Style>
</
Button>
</
ToolBar>
<
RichTextBox Name="richTextBox1" SelectionChanged="richTextBox1_SelectionChanged">
</
RichTextBox>

</
DockPanel>
</
Grid>
</
Window>

The procedure code(C#):

namespace RichTextBoxBoldHighlight
{
/// <summary>
///
Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{

public string FWeight
{
get { return (string)GetValue(FWeightProperty); }
set { SetValue(FWeightProperty,value); }
}

public static readonly DependencyProperty FWeightProperty =
DependencyProperty.Register("FWeight",
typeof(string),
typeof(Window1),
new FrameworkPropertyMetadata(""));

public Window1()
{
InitializeComponent();

}

private void ToggleBold_Click(object sender, RoutedEventArgs e)
{
EditingCommands.ToggleBold.Execute(null, richTextBox1);
UpdateSelectionFontWeight();
}

private void richTextBox1_SelectionChanged(object sender, RoutedEventArgs e)
{
UpdateSelectionFontWeight();

}

private void UpdateSelectionFontWeight()
{
TextRange tRange = new TextRange(richTextBox1.Selection.Start, richTextBox1.Selection.End);
FWeight = tRange.GetPropertyValue(Run.FontWeightProperty).ToString();
}


}
}

Hope it will help someone who needs such functionality.