Hi I'm trying to bind to the TextBox.CaretIndex
property which isn't a DependencyProperty
, so I created a Behavior
, but it doesn't work as expected.
Expectation (when focused)
- default = 0
- if I change the value in my view it should change the value in my viewmodel
- if I change the value in my viewmodel it should change the value in my view
Current behavior
- viewmodel value gets called ones when the window opens
Code-behind
public class TextBoxBehavior : DependencyObject
{
public static readonly DependencyProperty CursorPositionProperty =
DependencyProperty.Register(
"CursorPosition",
typeof(int),
typeof(TextBoxBehavior),
new FrameworkPropertyMetadata(
default(int),
new PropertyChangedCallback(CursorPositionChanged)));
public static void SetCursorPosition(DependencyObject dependencyObject, int i)
{
// breakpoint get never called
dependencyObject.SetValue(CursorPositionProperty, i);
}
public static int GetCursorPosition(DependencyObject dependencyObject)
{
// breakpoint get never called
return (int)dependencyObject.GetValue(CursorPositionProperty);
}
private static void CursorPositionChanged(
DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
// breakpoint get never called
//var textBox = dependencyObject as TextBox;
//if (textBox == null) return;
}
}
XAML
<TextBox Text="{Binding TextTemplate,UpdateSourceTrigger=PropertyChanged}"
local:TextBoxBehavior.CursorPosition="{Binding CursorPosition}"/>
Further Information
I think there is something really wrong here because I need to derive it from DependencyObject
which was never needed before, because CursorPositionProperty
is already a DependencyProperty
, so this should be enough. I also think I need to use some events in my Behavior
to set my CursorPositionProperty
correctly, but I don't know which.
As you said, the
TextBox.CaretIndex
Property is not aDependencyProperty
, so you cannot data bind to it. Even with your ownDependencyProperty
, it won't work... how would you expect to be notified whenTextBox.CaretIndex
Property changes?I encountered a similar problem, and the easiest solution for me was to inherit from TextBox and add a DependencyProperty. So it looks like this:
... and in my XAML:
... and CaretPosition property in the View Model of course. If you're not going to bind your View Model to other text-editing controls, this may be sufficient, if yes - you'll probably need another solution.
After fighting with my Behavior i can present you a 99% working solution
Behavior
XAML
there is just on thing i don't know why it doesn't work =>
BindsTwoWayByDefault = true
. it has no effect on the binding as far as i can tell you because of this i need to set the binding mode explicit in XAML