如何在代码中设置绑定?

113

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

但我似乎无法做得正确。

这是我尝试过的:

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

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

我做错了什么?

4个回答

219

替换:

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部分是从PathPath可以通过构造函数或Path属性设置)评估出来的。


15
你也可以使用txtText.SetBinding(TextBox.TextProperty,myBinding)代替最后一行,这样可以减少输入的代码量。 - Manish Dubey
6
静态方法的好处在于第一个参数被定义为DependencyObject,因此它使得数据绑定在不从FrameworkElement或FrameworkContentElement(例如Freezables)派生的对象上成为可能。 - FreddyFlares
谢谢您。在寻找这样的示例时有些困难。 - Jesse Roper
太好了!我该如何清除绑定? - Quark Soup

12

你需要将源数据更改为视图模型对象:

myBinding.Source = viewModelObject;

2
除了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)。

0

示例:

数据上下文:

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

创建绑定:
  new Binding("SomeString")
  {
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
  };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接