0

In my code I have declared, within the custom control ValidatingTextBox, the following dependency property:

public DependencyProperty visibleText = DependencyProperty.RegisterAttached("visText", typeof(String), typeof(ValidatingTextBox));
public String visText
{
    get { return theBox.Text; }
    set { theBox.Text = value; }
}

But when I try to use the xaml

<local:ValidatingTextBox>
    <ValidatingTextBox.visibleText>

    </ValidatingTextBox.visibleText>
</local:ValidatingTextBox>

it says that such a dependencyproperty doesn't exist within ValidatingTextBox. What am I doing wrong? Is there a better way to interact with the child text box of my custom control?

1 Answer 1

1

In the register method you registered it as visText, the name of the field does not have anything to do with the property itself. You also seem to define an attached property which is going to be used like a normal property, you should define it as a normal dependency-property.

Further you create two properties, a depedency property without a CLR-wrapper and a normal property by doing this:

public String visText
{
    get { return theBox.Text; }
    set { theBox.Text = value; }
}

It has nothing to do with the value of your actual depedency property since it never accesses it. Besides that the property field should be static and readonly.

Reading through the Depedency Properties Overview is advised as this is quite a mess, also have a look at the article on creating custom dependency properties which should be quite helpful.


To address your question of how to interact with the child controls: Create (proper) dependency properties and bind to them.

Since the property already exists on the child you can also reuse it with AddOwner:

public static readonly DependencyProperty TextProperty =
    TextBox.TextProperty.AddOwner(typeof(MyControl));
public string Text
{
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}
<!-- Assuming a usercontrol rather than a custom control -->
<!-- If you have a custom control and the child controls are created in code you can do the binding there -->
<UserControl ...
      Name="control">
    <!-- ... -->
    <TextBox Text="{Binding Text, ElementName=control}"/>
    <!-- ... -->
</UserControl>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.