在我的用户控件中绑定不起作用

时间:2011-02-07 16:57:43

标签: c# wpf binding

我有一个名为TextBoxAndMore的用户控件,它包含一个文本框(称为textBox1),旁边有一个“更多”按钮。在这个用户控件上,我有一个名为Text的属性。我希望这个Text属性镜像文本框中的文本。

我希望这个属性是可绑定的,所以在我的XAML中我可以将它绑定到我的ViewModel中名为Description的String属性,如下所示:

<my:TextBoxAndMore Text="{Binding Path=Description}" />

所以我有以下代码(由propdb片段生成):

    // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(String), typeof(TextBoxAndMore),
        new UIPropertyMetadata(String.Empty));

    public String Text
    {
        get { return (String)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

并且,在文本框中,我将此代码附加到TextChanged事件处理程序,其想法是当用户在文本框中键入时,此用户控件的Text属性随之更改:

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        Text = textBox1.Text;
    }

然而,最终结果是绑定似乎不起作用。输出窗口中没有错误,我的ViewModel中的Description属性只是没有设置(它保持为空)。

我确信这是显而易见的事情,但我对WPF很陌生,并希望得到一些指导。

1 个答案:

答案 0 :(得分:2)

我认为您需要配置双向绑定:

<my:TextBoxAndMore Text="{Binding Path=Description Mode=TwoWay}" />

您还可以删除控件中的TextChanged事件代码,并使用TwoWay绑定到控件的Text属性。

编辑:

&LT; - &GT; ==双向绑定......

TextBlockInControlsTemplate&lt; - &gt; TextDepPropInControl&lt; - &gt; DescriptionPropInVM

相关问题