简体   繁体   中英

Problem with DependencyProperty in custom control

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM