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

前端 未结 5 1943
再見小時候
再見小時候 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:14

    There is a bug in .NET 4 with one way to source bindings that it calls getter for OneWayToSource bindings thats why you are having this problem.You can verify it by putting breakpoint on tb.DataContext = _vm; you will find setter is called and just after that getter is called on Text property.You can resolve your problem by manually feeding the viewmodel values from view before assigning the datacontext..NET 4.5 resolves this issue. see here and here too

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
       Debug.Print("'Set DataContext' button clicked");       
        _vm.Text=tb.Text;
        tb.DataContext = _vm;
    }
    

提交回复
热议问题