views:

181

answers:

1

Using WPF, I am building a very simple document editor that will provide basic formatting capabilities such as the ability to modify the appearance of a user's text, i.e. underline, bold, change font size, etc.

I have implemented several RichTextBox for the user's inputs and would like to display a button illustrating the toggle state of the formatting options similar to Microsoft Word. For example, if the user presses CTRL+B, all entered text would be bold, and the "Bold" button to reflect this state (depressed).

At this point, the button's IsChecked property (using a custom button), is bound to a Property (IsSelectedTextBold). Using the richTextBox.SelectionChanged to detect selection changes, I call OnPropertyChanged("IsSelectedTextBold") (defined below). This works as expected; however, when a user highlights a word and presses CTRL+B, the selection's font weight is changed to bold but the button doesn't reflect the change since the richTextBox.SelectionChanged event is not raised. Looking for a method to detect when the user presses CTRL+B, I registered my own CommandBinding:

CommandManager.RegisterClassCommandBinding(typeof(RichTextBox),
    new CommandBinding(EditingCommands.ToggleBold, 
    new ExecutedRoutedEventHandler(ToggleBold_Executed),
    new CanExecuteRoutedEventHandler(ToggleBold_CanExecute)));

ToggleBold_Executed() implements toggling the bold and calls OnPropertyChanged("IsSelectedTextBold") to inform the button that a change has occurred.

For some reason, PropertyChanged is set to null and will not fire when raised from the ToggleBold_Executed() function, but works just fine when called by the richTextBox_SelectionChanged event.

As a side note, I have also considered binding the Button's IsChecked property to the RichTextBox.FontWeight (with a necessary converter). The only thing preventing me from doing this is having multiple RichTextBoxes. Not sure if I want to dynamically bind and unbind the button to the active RichTextBox.

Thanks for enduring the lengthy post - any help would be greatly appreciated. Thank you!

private void OnPropertyChanged(string propertyName)
{
  if (this.PropertyChanged != null)
  {
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}
+1  A: 

I still haven't discovered the answer to my original question but here is a blog posting that provides a solution to my objective: http://www.howtocode.net/software-development/general/extending-wpf-commands

Joel