我有一个我创建的名为 TextBoxAndMore 的用户控件,它包含一个文本框(称为 textBox1),旁边有一个“更多”按钮。在这个用户控件上,我有一个名为 Text 的属性。我希望此 Text 属性反射(reflect)文本框中的文本。
我希望这个属性是可绑定(bind)的,这样在我的 XAML 中我可以将它绑定(bind)到我的 ViewModel 中一个名为 Description 的字符串属性,如下所示:
<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;
}
然而,最终结果是绑定(bind)似乎根本不起作用。输出窗口中没有错误,我的 ViewModel 中的 Description 属性只是没有设置(它仍然为空)。
我敢肯定这是显而易见的事情,但我对 WPF 还很陌生,希望得到一些指导。
最佳答案
我认为你需要配置双向绑定(bind):
<my:TextBoxAndMore Text="{Binding Path=Description Mode=TwoWay}" />
您还可以删除控件中的 TextChanged 事件代码,并使用 TwoWay 绑定(bind)到控件的 Text 属性。
编辑:
<-> ==双向绑定(bind)...
TextBlockInControlsTemplate <-> TextDepPropInControl <-> DescriptionPropInVM
关于c# - 我的用户控件中的绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4924019/