如何在代码中设置绑定
本文关键字:设置 绑定 代码 | 更新日期: 2023-09-27 18:09:22
我需要在代码中设置一个绑定。
我好像做不好。
这是我尝试过的:
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");
}
}
设置属性时,属性没有更新。
我做错了什么?
Replace:
myBinding.Source = ViewModel.SomeString;
:
myBinding.Source = ViewModel;
的例子:
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);
您的源应该只是ViewModel
, .SomeString
部分从Path
评估(Path
可以由构造函数或Path
属性设置)。
您需要将source更改为viewmodel object:
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);
}
我们也有这样的情况,我们只是保存DataContext
到一个本地属性,并使用它来访问视图模型属性。选择当然是你的,我喜欢这种方法,因为它与其他方法更一致。您还可以添加一些验证,如空检查。如果你真的改变你的DataContext
周围,我认为它也会很好调用:
BindingOperations.ClearBinding(myText, TextBlock.TextProperty);
清除旧视图模型的绑定(事件处理程序中的e.oldValue
)。
示例:
DataContext:
class ViewModel
{
public string SomeString
{
get => someString;
set
{
someString = value;
OnPropertyChanged(nameof(SomeString));
}
}
}
创建绑定:
new Binding("SomeString")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};