Note that there are some explanatory texts on larger screens.

plurals
  1. POCommandBinding Interfering with INotifyPropertyChanged
    text
    copied!<p>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.</p> <p>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). </p> <p>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:</p> <pre><code>CommandManager.RegisterClassCommandBinding(typeof(RichTextBox), new CommandBinding(EditingCommands.ToggleBold, new ExecutedRoutedEventHandler(ToggleBold_Executed), new CanExecuteRoutedEventHandler(ToggleBold_CanExecute))); </code></pre> <p>ToggleBold_Executed() implements toggling the bold and calls OnPropertyChanged("IsSelectedTextBold") to inform the button that a change has occurred. </p> <p>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. </p> <p>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. </p> <p>Thanks for enduring the lengthy post - any help would be greatly appreciated. Thank you!</p> <pre><code>private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload