【问题标题】:Binding DependencyProperty to DependencyProperty only working in one direction将 DependencyProperty 绑定到 DependencyProperty 仅在一个方向上工作
【发布时间】:2017-04-19 08:45:50
【问题描述】:

我正在使用带有 C# 的 WPF。 我有一个包含文本框的自定义控件。自定义控件有一个依赖属性FilterText。我的 ViewModel 的 CurrentText 属性绑定到我的控件的 FilterText 属性。

目标是当 TextBox 的 Text 属性发生变化时,这会更新我的 ViewModel 的 CurrentText 属性。

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

自定义用户控件:

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

用户控件代码隐藏中的依赖属性:

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

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

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

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

我的 generalQuickSearch 控件上的 FilterText 属性:

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

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    发现问题及解决方法: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。

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2012-04-15
      • 2012-01-31
      • 2014-11-19
      • 1970-01-01
      相关资源
      最近更新 更多