Nice programing

코드에서 바인딩을 설정하는 방법은 무엇입니까?

nicepro 2020. 10. 4. 13:26
반응형

코드에서 바인딩을 설정하는 방법은 무엇입니까?


코드에서 바인딩을 설정해야합니다.

나는 그것을 올바르게 얻을 수없는 것 같다.

이것이 내가 시도한 것입니다.

XAML :

<TextBox Name="txtText"></TextBox>

뒤에있는 코드 :

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

ViewModel :

public string SomeString
    {
      get
      { 
          return someString;
      }
      set 
      { 
          someString= value;
          OnPropertyChanged("SomeString");
      }
    }

속성을 설정할 때 업데이트되지 않습니다.

내가 도대체 ​​뭘 잘못하고있는 겁니까?


이 시도:

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);

를 지정하면 path(당신이 생성자에서처럼), 소스 그냥해야 ViewModel.SomeString부분은 경로에서 평가된다.


소스를 viewmodel 객체로 변경해야합니다.

myBinding.Source = viewModelObject;

Dyppl의 답변 외에도 OnDataContextChanged 이벤트 내부에 배치하는 것이 좋을 것이라고 생각합니다.

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the datacontext to a local property and used that to access viewmodel properties. The choice is of course yours, i like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your datacontext around, I think it would be nice to also call BindingOperations.ClearBinding(myText, TextBlock.TextProperty); to clear the binding of the old viewmodel (e.oldValue in the event handler).

참고URL : https://stackoverflow.com/questions/7525185/how-to-set-a-binding-in-code

반응형