Mode = OneWay 在直接赋值给 DependencyProperty 时绑定中断

Binding broken for Mode = OneWay on direct value assignment to DependencyProperty

我有一段非常简单的代码来理解当我们将绑定表达式分配给任何依赖项 属性 然后将直接值分配给该依赖项 属性 时发生的行为。以下是代码

查看XAML

<StackPanel>
    <Button Click="Button_Click" Content="Assign binding value" />
    <Button Click="Button_Click_1" Content="Assign direct value" />
    <TextBox Text="{Binding TextSource, Mode=OneWay}" x:Name="stf" />
</StackPanel>

查看XAML.cs

public partial class MainWindow : Window
{
    MainViewViewModel vm = new MainViewViewModel();
    public MainWindow()
    {
        InitializeComponent();

        DataContext = vm;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        vm.TextSource = "Value set using binding";
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        stf.Text = "New direct value";
    }
}

ViewModel

public class MainViewViewModel : INotifyPropertyChanged
{
    //INotifypropertychanged implementation here ...

    private string _textSource;

    public string TextSource
    {
        get { return _textSource; }
        set
        {
            _textSource = value;
            OnPropertyChanged("TextSource");
        }
    }

}

现在我的观察是

  1. 当我单击 "Assign binding value" 时,视图会更新为绑定源值。 (符合预期)
  2. 当我单击 "Assign direct value" 时,视图会更新为分配给文本字段的直接值(正如预期的那样
  3. 我假设在这个阶段绑定被破坏,当我再次点击 "Assign binding value" 它应该不起作用,意味着没有 UI 更新。它按照我的预期工作(如预期
  4. 令人困惑的一点是,当我将绑定模式设置为"TwoWay"时,第3点没有发生,无论我按下什么按钮,它总是保持工作。来自绑定源和直接值。 (我不清楚 TwoWay 绑定需要用这个做什么

谁能解释一下?

我认为TwoWay绑定会将View Model中属性的值赋值给UI元素的依赖属性, 并且 如果您在任何时候更改依赖项 属性 的值(例如当您按下按钮 "Assign direct value" 时),那么依赖项 属性 的新值将也被分配给视图模型中的 属性。

换句话说,我认为 TowWay 模式实际上意味着可以将值从 View Model 分配给 UI 以及从 UI 分配给 View Model。

在设置 DependencyProperty 值时,DependencyObject 检查新值是否为 BindingExpression。如果不是,它检查先前的值是否是绑定表达式。对于先前的绑定表达式,它会尝试设置表达式的值。 BindingExpression 在尝试设置值时检查模式,对于 OneWay,它 returns false 而不设置值并停用和分离依赖项 属性 的绑定表达式。因此,对于 Mode=OnWay,绑定会因依赖项 属性.

而被停用和分离

对于 TwoWay,由于 BindingExpression 能够设置值,因此绑定不会停用并继续工作。