为什么数据绑定在OneWay模式下中断?

Gis*_*shu 8 data-binding wpf binding-mode

这是一个小的XAML片段.你会看见

<StackPanel>
     <TextBox x:Name="txtValue">250</TextBox>
     <Slider x:Name="slide" 
             Value="{Binding ElementName=txtValue, Path=Text, 
                             Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" 
            Minimum="0" Maximum="500"></Slider>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
  1. 更改文本框值时,滑块会更新
  2. 如果显式更改滑块值,则先前的行为会中断,即停止工作.

如果我删除Mode=OneWayset指令(默认为双向),一切都很完美.

为什么会这样?

小智 12

使用mode=TwoWay并设置UpdateSourceTrigger=Explicit.

  • 这有效...但没有解释任何原因. (7认同)

Ale*_*zik 2

您的数据绑定并未损坏,而是已停用(http://en.wikipedia.org/wiki/Euphemism):

System.Windows.Data Warning: 75 : BindingExpression (hash=52697953): Deactivate
System.Windows.Data Warning: 99 : BindingExpression (hash=52697953): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 59 : BindingExpression (hash=52697953): Detach
Run Code Online (Sandbox Code Playgroud)

如果您移动滑块,将跟踪级别设置为高将在 VS 输出窗口中生成此消息:

<Slider xmlns:trace="clr-namespace:System.Diagnostics;assembly=WindowsBase"
        Value="{Binding trace:PresentationTraceSources.TraceLevel=High,
            ElementName=txtValue, Path=Text, Mode=OneWay,
            UpdateSourceTrigger=PropertyChanged}"
        Minimum="0" Maximum="500"></Slider>
Run Code Online (Sandbox Code Playgroud)

  • 为什么它会分离?如果在绑定控件上移动拇指之类的操作会停用或取消绑定,那么它就违背了单向绑定的目的。通过破坏,我的意思是不再看到预期的行为。 (5认同)