0

I'm trying to replace the SelectedText of a TextBox with a new value by binding on the custom property 'Selected'. Currently, updating Selected through binding doesn't change the actual SelectedText. I'm almost there I think; at least mouse-selecting text is updating Selected.

I'd prefer solutions based on inheriting from TextBox if possible. Can anybody tell me what's missing please?

class SelectionTextbox : TextBox
{
    public static readonly DependencyProperty SelectionProperty = DependencyProperty.Register("Selection", typeof(string), typeof(SelectionTextbox));

    public string Selection
    {
        get
        {
            return (string)base.GetValue(SelectionProperty);
        }
        set
        {
            base.SetValue(SelectionProperty, value);
        }
    }
    protected override void OnSelectionChanged(RoutedEventArgs e)
    {
        base.OnSelectionChanged(e);
        Selection = SelectedText;
    }
}
arbitrary
  • 103
  • 9

2 Answers2

2

The problem is, that you never actually do anything with the value you assign to Selection. You need to actually make it the selected text.

public string Selection
{
    get
    {
        return (string)base.GetValue(SelectionProperty);
    }
    set
    {
        base.SetValue(SelectionProperty, value);
        if(value != SelectedText)
            SelectedText = value;
    }
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
2

For Binding to update the source you have to specify Mode=TwoWay if you want to reflect changes back to code. This can be done by two ways:

Selection="{Binding Path=MyProperty, Mode=TwoWay}"

or by

public static readonly DependencyProperty SelectionProperty = 
    DependencyProperty.Register("Selection",
        typeof(string),
        typeof(SelectionTextbox),
        new FrameworkPropertyMetadata(default(string), 
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

By using the second method you have that all bindings to Selection are done TwoWay and you do not have to specify it explicitly.

Michael Mairegger
  • 6,833
  • 28
  • 41