How to set a binding in Code?

后端 未结 3 1120
深忆病人
深忆病人 2020-11-28 04:20

I have the need to set a binding in code.

I can\'t seem to get it right tho.

This is what i have tried:

XAML:



        
3条回答
  •  广开言路
    2020-11-28 05:10

    Replace:

    myBinding.Source = ViewModel.SomeString;
    

    with:

    myBinding.Source = ViewModel;
    

    Example:

    Binding myBinding = new Binding();
    myBinding.Source = ViewModel;
    myBinding.Path = new PropertyPath("SomeString");
    myBinding.Mode = BindingMode.TwoWay;
    myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);
    

    Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

提交回复
热议问题