【发布时间】:2011-02-07 16:57:42
【问题描述】:
我创建了一个名为 TextBoxAndMore 的用户控件,其中包含一个文本框(称为 textBox1),旁边有一个“更多”按钮。在这个用户控件上,我有一个名为 Text 的属性。我希望这个 Text 属性能够镜像文本框中的文本。
我希望这个属性是可绑定的,以便在我的 XAML 中我可以将它绑定到我的 ViewModel 中名为 Description 的字符串属性,如下所示:
<my:TextBoxAndMore Text="{Binding Path=Description}" />
所以我有以下代码(由 propdb sn-p 生成):
// 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 还是很陌生,希望得到一些指导。
【问题讨论】:
-
您希望将绑定更改为
TwoWay,而不是TextChanged处理程序,以便用户所做的更新自动返回到属性。 -
谢谢,我已将 XAML 更改为
<my:TextBoxAndMore Text="{Binding Path=Security, Mode=TwoWay}" />(这是您的意思吗?)但我似乎仍然遇到同样的问题。