Question

I have a Custom user control in a silver light Project.

I use it in other page and want to Pass textbox to Custom User control.

For this I create dependcy as below :

    public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("TextBoxControl", typeof(TextBox), typeof(SpellCheck), new PropertyMetadata(false));
    public TextBox TextBoxControl
    {
        get { return (TextBox)GetValue(MyPropertyProperty); }
        set
        {
            SetValue(MyPropertyProperty, value);
            TextSpell = value;
        }
    }

Here TextSpell is a textbox.

And I use this property in a silver light page as below:

<TextBox x:Name="txtNote" Grid.Row="3" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Stretch" Width="400"/>
<myButton:SpellCheck x:Name="btnSpell" Grid.Row="3" TextBoxControl="txtNote"  Grid.Column="1" Width="20" Height="20"  Margin="403,0,0,0" HorizontalAlignment="Left"/>

But I give s me a error : "The Typeconvertor for Texbox dose not support converting from a string"

So How can I pass a text box in custom usercontrol.

Thanks, Hitesh

Was it helpful?

Solution

You can not simply use the field name (x:Name) string of the TextBox as a value for your TextBoxControl property. Instead you may use an ElementName binding like this:

<myButton:SpellCheck TextBoxControl="{Binding ElementName=txtNote}" ... />

And there are more things wrong:

  • In the CLR wrappers of a dependency property, you should never call anything else than GetValue and SetValue. The explanation is given in the XAML Loading and Dependency Properties article on MSDN. Instead, you have to have a PropertyChangedCallback registered with the property metadata.

  • There is a naming convention for the static dependency property fields. They should be named like the property, with a trailing Property.

  • The default value has to match the property type. Your false value is not valid, and might be null instead. But as that is the default anyway, you should leave it out completely.

The declaration would now look like this:

public static readonly DependencyProperty TextBoxControlProperty =
    DependencyProperty.Register(
        "TextBoxControl", typeof(TextBox), typeof(SpellCheck),
        new PropertyMetadata(TextBoxControlPropertyChanged));

public TextBox TextBoxControl
{
    get { return (TextBox)GetValue(TextBoxControlProperty); }
    set { SetValue(TextBoxControlProperty, value); }
}

private static void TextBoxControlPropertyChanged(
    DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    var spellCheck = (SpellCheck)obj;
    spellCheck.TextSpell = (TextBox)e.NewValue;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top