WPF binding OneWayToSource sets source property to “” when the DataContext is changed

前端 未结 5 1944
再見小時候
再見小時候 2021-01-19 00:22

I have a OneWayToSource binding that is not behaving as I expected when I set the DataContext of the target control. The property of the source is being set to default inste

5条回答
  •  别那么骄傲
    2021-01-19 01:00

    TextBox has a Binding in it's TextProperty and when you set TextBox's DataContext, TextBox will update it's source (viewmodel.Text) , no matter which type of the UpdateSourceTrigger.

    It's said that the first output in viewmodel

    "ViewModel.Text (old value=, new value=)"

    is not triggered by UpdateSourceTrigger=PropertyChanged.

    It's just a process of init:

    private string _Text;
    public string Text
    {
        get { return _Text; }
        set
        {
            Debug.Print(
               "ViewModel.Text (old value=" + (_Text ?? "") +
               ", new value=" + (value ?? "") + ")");
            _Text = value;
        }
    }
    

    Because it's not triggered by UpdateSourceTrigger=PropertyChanged, the viewmodel will not know the value of TextBox.Text.

    When you type "Y",the trigger of PropertyChanged will working,so the viewmodel read text of TextBox.

提交回复
热议问题