views:

299

answers:

1

I have a user control that has a textbox. I have tried to expose the texbox's Text property by implementing a DependencyProperty with the same name in the UserControl. Thus:

public static readonly DependencyProperty TextProperty =
   DependencyProperty.Register("Text",
                                typeof(string),
                                typeof(UserControlWithTextBox),
                                new UIPropertyMetadata(string.Empty));
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set 
        {
            SetValue(TextProperty, value);
            textBox.Text = value;
        }
    }

The get part seems to work OK in my application. However, I tried to bind the IsEnabled property of a button to the Text property of two of these UserControls using a converter that will check if both UserControls' Text properties are empty strings. I get the following error when the application window loads:

System.InvalidCastException was unhandled Message="Cannot convert an object of type MS.Internal.NamedObject to type System.String."

The Convert method looks thus:

  public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return (string) values[0] != string.Empty &&
               (string) values[1] != string.Empty;
    }

values[0] and values[1] both have the value DependencyProperty.UnsetValue when the exception is thrown.

Where have I gone wrong?

+1  A: 

Judging by your Exception values[0] and values[1] are not String so when you try to explicitly cast them it breaks.

To avoid these types of things you should really bind your TextBoxes to public properties then bind your buttons IsEnabled to another public property that in the getter will check if the TextBoxes are empty by checking the properties they are bound to.

Stan R.
Thank you. The problem was much simpler than I thought. I forgot to rename the ElementName="MyUserControlInstance" after renaming the UserControl instance itself...
Dabblernl
Sometimes its the little things that drive you crazy...oh who am I kidding its all the time.. :)
Stan R.