2011-06-21 53 views
0

在我的代码我已经宣布,自定义控制ValidatingTextBox内,以下依赖属性:问题与DependencyProperty的自定义控制

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

但是当我尝试使用XAML

<local:ValidatingTextBox> 
    <ValidatingTextBox.visibleText> 

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

它说在ValidatingTextBox中不存在这样的依赖属性。我究竟做错了什么?有没有更好的方式与我的自定义控件的子文本框进行交互?

回答

1

在注册方法中,您将其注册为visText,该字段的名称与该属性本身没有任何关系。你似乎也定义了一个将被用作普通属性的附加属性,你应该把它定义为一个普通的依赖属性。

而且创建两个属性,一个depedency属性,而不使用CLR的包装,并通过这样一个正常的属性:

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

它无关,与你的实际depedency财产的价值,因为它从来没有访问它。除此之外,属性字段应该是静态的和只读的。

通过Depedency Properties Overview阅读建议,因为这是一个相当混乱,也有看看the article on creating custom dependency properties这应该是相当有益的。


要解决您如何与子控件进行交互的问题:创建(适当的)依赖项属性并绑定到它们。

由于财产上的孩子已经存在,你也可以用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>