将DependencyProperty绑定到DependencyProperty仅在一个方向上工作

时间:2017-04-19 08:45:51

标签: wpf binding

我在WP#中使用WPF。 我有一个包含TextBox的自定义控件。自定义控件具有依赖项属性FilterText。我的ViewModel的CurrentText属性绑定到我的控件的FilterText属性。

目标是当TextBox的Text-property更改时,这会更新ViewModel的CurrentText属性。

问题:更新TextBox的文本并不会更新我的控件的FilterText DP。但是,更改FilterText属性会更新TextBox的文本。

自定义用户控件:

<UserControl x:Name="generalQuickSearch" (..)>
(..)
     <TextBox Text="{Binding FilterText, ElementName=generalQuickSearch, Mode=TwoWay}"/>
(..)
</UserControl>

usercontrol的代码隐藏中的依赖属性:

 public static readonly DependencyProperty FilterTextProperty = DependencyProperty.Register("FilterText", typeof(string), typeof(GeneralQuickSearch));

在我看来,使用自定义控件:

<controls:GeneralQuickSearch FilterText="{Binding CurrentText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

使用Snoop,当我在文本框中输入文字时:

Text property of the TextBox

我的generalQuickSearch控件上的FilterText属性:

FilterText property on GeneralQuickSearch control

我不知道为什么这不起作用。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

发现问题和解决方案:默认情况下,TextBox的Text属性仅在LostFocus上更新。这可以通过将其添加到绑定来更改:

UpdateSourceTrigger=PropertyChanged

来源:https://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

  

默认值为Default,它返回目标依赖项属性的默认UpdateSourceTrigger值。但是,大多数依赖项属性的默认值是PropertyChanged,而Text属性的默认值是LostFocus。

相关问题