코드에서 바인딩을 설정하는 방법은 무엇입니까?
코드에서 바인딩을 설정해야합니다.
나는 그것을 올바르게 얻을 수없는 것 같다.
이것이 내가 시도한 것입니다.
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
'Nice programing' 카테고리의 다른 글
ContextMenuStrip이 사용 된 컨트롤 확인 (0) | 2020.10.05 |
---|---|
JavaScript로 SVG의 Z 인덱스 / 레이어를 변경할 수 있습니까? (0) | 2020.10.04 |
버튼의 드로어 블을 축소하려면 어떻게해야합니까? (0) | 2020.10.04 |
C / C ++ : 강제 비트 필드 순서 및 정렬 (0) | 2020.10.04 |
interface {}를 int로 변환 (0) | 2020.10.04 |