当我们像这样将 textblock.Text 与 Textbox 的文本长度绑定时
<TextBox x:Name="txtName" Grid.Row="0" />
<TextBlock Text="{Binding ElementName=txtName, Path=Text.Length}" Grid.Row="1" />
Textblock 的 Text 会随着 txtName 的文本实时变化。但是当我在 WPF 用户控件中定义一个新的 DependencyProperty 时,如下所示:
//MyCustomUC.xaml.cs
static FrameworkPropertyMetadata propertymetadata = new FrameworkPropertyMetadata("Comes as Default", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(MyCustom_PropertyChanged), new CoerceValueCallback(MyCustom_CoerceValue), false, UpdateSourceTrigger.PropertyChanged);
public static readonly DependencyProperty MyCustomProperty = DependencyProperty.Register("MyCustom", typeof(string), typeof(MyCustomUC), propertymetadata, new ValidateValueCallback(MyCustom_Validate));
public string MyCustom
{
get
{
return this.GetValue(MyCustomProperty) as string;
}
set
{
this.SetValue(MyCustomProperty, value);
}
}
并将其绑定到文本框
//MyCustomUC.xaml
<UserControl ... x:Name="ucs" ...>
<TextBox Text="{Binding ElementName=ucs, Path=MyCustom}"></TextBox>
</UserControl>
//MainWindow.xaml
<local:MyCustomUC x:Name="ucust" Grid.Row="0" />
<TextBox x:Name="tbChange" Text="{Binding ElementName=ucust, Path=MyCustom}" Grid.Row="1"/>
在文本框失去焦点之前,似乎“MyCustom”不会改变。当文本框中的文本实时更改时,如何更改它?先感谢您。