WPF TextBlock 绑定停用和分离

WPF TextBlock binding deactivate & detach

我开始发现我的文本块上的某些绑定存在异常问题:

XAML

  <TextBlock Text="{Binding PartCount,FallbackValue=1, UpdateSourceTrigger=PropertyChanged, diag:PresentationTraceSources.TraceLevel=High}" Foreground="Black" Margin="-3"/>

我确定我的绑定路径解析是正确的,因为如果我将此块更改为包含内容而不是文本的标签,那么它就可以正常工作。

我为绑定启用了诊断记录器,我可以看到它正确初始化并从其来源设置初始值:

调试日志

System.Windows.Data Warning: 67 : BindingExpression (hash=40999308): Resolving source (last chance) System.Windows.Data Warning: 70 : BindingExpression (hash=40999308): Found data context element: TextBlock (hash=5477191) (OK) System.Windows.Data Warning: 78 : BindingExpression (hash=40999308): Activate with root item LoadStack (hash=22395825) System.Windows.Data Warning: 107 : BindingExpression (hash=40999308): At level 0 using cached accessor for LoadStack.PartCount: RuntimePropertyInfo(PartCount) System.Windows.Data Warning: 104 : BindingExpression (hash=40999308): Replace item at level 0 with LoadStack (hash=22395825), using accessor RuntimePropertyInfo(PartCount) System.Windows.Data Warning: 101 : BindingExpression (hash=40999308): GetValue at level 0 from LoadStack (hash=22395825) using RuntimePropertyInfo(PartCount): 'Infinity' System.Windows.Data Warning: 80 : BindingExpression (hash=40999308): TransferValue - got raw value 'Infinity' System.Windows.Data Warning: 84 : BindingExpression (hash=40999308): TransferValue - implicit converter produced '∞' System.Windows.Data Warning: 89 : BindingExpression (hash=40999308): TransferValue - using final value '∞'

但是,当我导航到显示此文本框的 window 时,我得到了:

调试日志

System.Windows.Data Warning: 79 : BindingExpression (hash=40999308): Deactivate System.Windows.Data Warning: 103 : BindingExpression (hash=40999308): Replace item at level 0 with {NullDataItem} System.Windows.Data Warning: 63 : BindingExpression (hash=40999308): Detach

所以在这一点之后,视觉元素不会更新,但当源发生如下变化时,我仍然会在日志中获取信息:

调试日志

System.Windows.Data Warning: 95 : BindingExpression (hash=53188122): Got PropertyChanged event from LoadStack (hash=22395825) System.Windows.Data Warning: 101 : BindingExpression (hash=53188122): GetValue at level 0 from LoadStack (hash=22395825) using RuntimePropertyInfo(PartCount): '50' System.Windows.Data Warning: 80 : BindingExpression (hash=53188122): TransferValue - got raw value '50' System.Windows.Data Warning: 84 : BindingExpression (hash=53188122): TransferValue - implicit converter produced '50' System.Windows.Data Warning: 89 : BindingExpression (hash=53188122): TransferValue - using final value '50'

所以有些东西导致了“停用”和“分离”,这意味着它不再更新视图。我已经检查过数据上下文是否一致,确实如此。

有什么可以导致绑定以这种方式响应的吗?

分离行为通常发生在数据绑定之外设置的值时。

方法是检查您是否在其他地方设置 TextBlock.Text(例如,在后面的代码中或在您的 XAML 中)。

另一种可能性是您的 viewmodel 实例被另一个替换。