views:

49

answers:

1

Hello,

I'm trying to overcome a limitation that doesn't allow me to bind to regular clr properties.

The solution I use uses custom dependency properties that in turn changes clr properties.

Here is the code

class BindableTextBox : TextBox
{
    public static readonly DependencyProperty BoundSelectionStartProperty = DependencyProperty.Register("BoundSelctionStart", typeof(int), typeof(BindableTextBox),
                                                                                                          new PropertyMetadata(new PropertyChangedCallback(BindableTextBox.onBoundSelectionStartChanged)));

    private static void onBoundSelectionStartChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((TextBox)d).SelectionStart = (int)e.NewValue;
    }

    private static readonly DependencyProperty BoundSelectionLenghtProperty = DependencyProperty.Register("BoundSelectionLenght", typeof(int), typeof(BindableTextBox),
                                                                                                            new PropertyMetadata(new PropertyChangedCallback(BindableTextBox.onBoundSelectionLenghtChanged)));

    private static void onBoundSelectionLenghtChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((TextBox)d).SelectionLength = (int)e.NewValue;
    }

    public int BoundSelectionStart
    {
        get { return (int)GetValue(BoundSelectionStartProperty); }
        set { SetValue(BoundSelectionStartProperty, value); }
    }

    public int BoundSelectionLenght
    {
        get { return (int)GetValue(BoundSelectionLenghtProperty); }
        set { SetValue(BoundSelectionLenghtProperty, value); }
    }
}

But when I try to bound something to BoundSelectionStart it says it says that I can only bind to DP.

<bindable:BindableTextBox Text="{Binding Name}" BoundSelectionStart="{Binding ElementName=slider1, Path=Value}" />

What is the problem?

+1  A: 

You have a typo in the line:

public static readonly DependencyProperty BoundSelectionStartProperty = DependencyProperty.Register(...)

The first parameter should be "BoundSelectionStart" (2x e in Selection), not "BoundSelctionStart".

Paul Baker
You've also misspelled "Length" as "Lenght" in several places.
Paul Baker
Thanks, I should buy myself a pair of glasses :)
kamilo