【发布时间】:2013-03-26 03:25:33
【问题描述】:
当我们像这样将 textblock.Text 与 Textbox 的文本长度绑定时
<TextBox x:Name="txtName" Grid.Row="0" />
<TextBlock Text="{Binding ElementName=txtName, Path=Text.Length}" Grid.Row="1" />
Textblock 的文本会随着 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”似乎不会改变。当文本框中的文本实时更改时,如何更改它? 提前谢谢你。
【问题讨论】:
标签: wpf binding real-time dependency-properties