如何在代码中设置绑定?

Posted

技术标签:

【中文标题】如何在代码中设置绑定?【英文标题】:How to set a binding in Code? 【发布时间】:2011-11-23 10:07:31 【问题描述】:

我需要在代码中设置绑定。

我好像没弄好。

这是我尝试过的:

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

视图模型:

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

当我设置它时,该属性没有更新。

我做错了什么?

【问题讨论】:

【参考方案1】:

替换:

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 属性设置)。

【讨论】:

您也可以使用 txtText.SetBinding(TextBox.TextProperty,myBinding) 代替最后一行,以减少打字:) @ManishDubey 静态方法的好处是第一个参数被定义为一个 DependencyObject,因此它可以对不是从 FrameworkElement 或 FrameworkContentElement 派生的对象(例如 Freezables)进行数据绑定。 谢谢。努力寻找这样的例子【参考方案2】:

您需要将源更改为 viewmodel 对象:

myBinding.Source = viewModelObject;

【讨论】:

【参考方案3】:

除了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 保存到本地属性并使用它来访问视图模型属性。选择当然是你的,我喜欢这种方法,因为它与其他方法更一致。您还可以添加一些验证,例如空检查。如果你真的改变了你的DataContext,我认为也可以打电话:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

清除旧视图模型的绑定(事件处理程序中的e.oldValue)。

【讨论】:

【参考方案4】:

例子:

数据上下文:

  class ViewModel
  
    public string SomeString
    
      get => someString;
      set 
      
        someString = value;
        OnPropertyChanged(nameof(SomeString));
      
    
  

创建绑定:

  new Binding("SomeString")
  
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
  ;

【讨论】:

以上是关于如何在代码中设置绑定?的主要内容,如果未能解决你的问题,请参考以下文章

如何在角度6的下拉列表中设置双向绑定数据?

在 WCF 服务中设置绑定

遵循MVVM模式,如何创建“设置”功能,在其他用户控件中设置数据绑定项值?

如何在 Scintilla 中设置边距蒙版?

如何在 LDAP 中设置正确的访问指令?

C# WPF中设置绑定时,INotifyPropertyChanged接口如何对数组使用