我需要在代码中设置绑定。
不过,我似乎还是做不好。
这是我尝试过的:
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");
}
}
当我设置该属性时,它没有更新。
我做错了什么?
发布于 2011-09-23 14:45:50
替换:
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
属性设置)。
发布于 2011-09-23 14:47:43
您需要将source更改为viewmodel对象:
myBinding.Source = viewModelObject;
发布于 2019-09-04 15:11:32
除了Dyppl的answer之外,我认为把它放在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
保存到本地属性,并使用它来访问视图模型属性。当然,这是您的选择,我喜欢这种方法,因为它与其他方法更一致。您还可以添加一些验证,如null检查。如果你真的改变了你的DataContext
,我想也可以调用:
BindingOperations.ClearBinding(myText, TextBlock.TextProperty);
清除旧视图模型的绑定(事件处理程序中的e.oldValue
)。
https://stackoverflow.com/questions/7525185
复制相似问题