使用dependencyProperty将文本框从页面传递到Custom usercontrol

时间:2014-05-09 06:24:42

标签: silverlight silverlight-4.0 silverlight-5.0

我在银灯项目中有自定义用户控件。

我在其他页面中使用它并希望将文本框传递给自定义用户控件。

为此,我创建了以下的依赖:

    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;
        }
    }

此处TextSpell是一个文本框。

我在银灯页面中使用此属性如下:

<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"/>

但我给了我一个错误:&#34; Texbox的Typeconvertor不支持从字符串转换&#34;

那么如何在自定义用户控件中传递文本框。

谢谢, 亚太区首席技术官Matt

1 个答案:

答案 0 :(得分:1)

您不能简单地使用TextBox的字段名称(x:Name)字符串作为TextBoxControl属性的值。相反,您可以像这样使用ElementName绑定:

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

还有更多错误:

  • 在依赖项属性的CLR包装器中,除了GetValueSetValue之外,不应该调用任何其他内容。有关MSDN的XAML Loading and Dependency Properties文章中给出了解释。相反,您必须在属性元数据中注册PropertyChangedCallback

  • 静态依赖项属性字段有一个命名约定。它们应该像属性一样命名,并带有尾随属性

  • 默认值必须与属性类型匹配。您的false值无效,可能是null。但是因为这是默认的,你应该把它完全抛弃。

声明现在看起来像这样:

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;
}
相关问题