Take the 2-minute tour ×

I have a wpf application where I extended the RichTextBox to provide some specific functions. Lets call that new class BetterTextBox.

Now, when I click in that TextBox TextBox.OnPreviewMouseLeftButtonUp is called and I am getting the CaretPosition:

    protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
        PressedOffset = Document.ContentStart.GetOffsetToPosition(CaretPosition);      

    public static readonly DependencyProperty PressedOffsetProperty 
          = DependencyProperty.Register("PressedOffset", typeof(int),
            new FrameworkPropertyMetadata()
            DefaultValue = 0,
            BindsTwoWayByDefault = true,
            DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,

    public int PressedOffset
        get { return (int)GetValue(PressedOffsetProperty); }
        set { SetValue(PressedOffsetProperty, value); Console.WriteLine("klöjgf");}


<Window x:Name="MainWindow">
    <BetterTextBox />

MainWindow has MainViewModel as DataContext. What I want to do is, when a MouseClick in BetterTextBox occurs, a function in MainViewModel should be called. How can I get out of my UserControl a call a function in the MainViewModel?

I tried something like this:

<Window x:Name="MainWindow">
   <BetterTextBox PressedOffset="{Binding ElementName=MainWindow, Path=MyFunction"/>


public int MyFunction
     set { callMyRealFunction(); }

But that doesn't work. There is also a way to register a CallbackFunction for PressedOffsetProperty, but I am not sure how to register there a function from the MainViewModel which is not static.

share|improve this question
add comment

2 Answers

Create another dependency property of type ICommand say 'TextClickCommand'. Create a command in your viewmodel and bind to TextClickCommand and execute this on MouseClick.

Edit: You can do it even the other way around create a IsTextSelected bool dependency property in textbox bind to this bool using a propery in view model and call your method in view model property setter.

share|improve this answer
Sry, I can't really follow you. Can you be more precisly? I am already doing your "Edit" without luck or not? I also googled for Commands and there is a bunch of results and I am getting lost. –  KasF Jun 30 '11 at 7:57
add comment
up vote 0 down vote accepted

Just solved by doing

<BetterTextBox PressedOffset="{Binding Path=Parent.DataContext.SelectFromOffset,
      RelativeSource={RelativeSource Self}}"/>

from WPF Usercontrol interaction with parent view / viewmodel

share|improve this answer
add comment

Your Answer


