当我们绑定textblock。长度与文本框长度相同的文本
<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"将不会改变,直到文本框失去焦点。我怎样才能使它被改变时,文本框中的文本在实时?
<TextBox x:Name="tbChange" Text="{Binding ElementName=ucust, Path=MyCustom, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1"/>