C#C
C#3y ago
Twiner

Sanity check on WPF CustomControl Binding to ViewModel not working

Can someone sanity check me here...
In WPF I have a custom control derived from RichTextBox.
I needed to have a way to access the selected text from my ViewModel so I could use it to inject into a new object created by said VM
However, the value doesn't seem to move across the binding into the view model.

So on my view model I made a SelectedText Property
public class MyViewModel : INotifyPropertyChanged {
  public event PropertyChangedEventHandler? PropertyChanged;
  private string _selectedText;
  public string SelectedText { 
    get => _selectedText; 
    set { _selectedText = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedText))); }
  }
}

and in my custom RichTextBox I have a DependencyProperty
public class AlertTextBox: RichTextBox {
  public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.Register(nameof(SelectedText), typeof(string), typeof(AlertTextBox));
  public string SelectedText
  {
    get => (string)GetValue(SelectedTextProperty);
    set => SetValue(SelectedTextProperty, value);
  }
  public AlertTextBox(){
    Selection.Changed += SelectionChanged;
  }
  public void SelectionChanged(object sender, EventArgs e) => SetCurrentValue(SelectedTextProperty, Selection.Text);
}

Finally, in my test Window I have it bound together
   <AlertTextBox SelectedText="{Binding Path=SelectedText}" />


When inspecting the UI with Snoop, I can see that the binding on SelectedText is considered valid.
I believe that using SetCurrentValue is correct to allow the value to propagate across the binding to the ViewModel

So I must be missing something, I've done this what feels like countless times and I just don't see what I'm overlooking
Was this page helpful?