如何在Code中设置绑定?


96

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

我似乎无法正确理解。

这是我尝试过的:

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

设置时属性未更新。

我究竟做错了什么?

Answers:


193

更换:

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

您的来源应该是just ViewModel.SomeString部分是从中评估的PathPath可以由构造函数或Path属性设置)。


14
您也可以使用txtText.SetBinding(TextBox.TextProperty,myBinding)代替最后一行,只是为了减少打字:)
Manish Dubey 2015年

5
@ManishDubey静态方法的好处在于,第一个参数定义为DependencyObject,因此它可以对不是从FrameworkElement或FrameworkContentElement派生的对象(例如Freezables)进行数据绑定。
FreddyFlares

谢谢你 苦苦寻找这样的例子
Jesse Roper

11

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

myBinding.Source = viewModelObject;

1

除了 答案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);
}

我们还遇到过一些情况,就是我们只是将DataContextd 保存到本地属性,并使用它来访问viewmodel属性。选择当然是您的选择,我喜欢这种方法,因为它与其他方法更加一致。您还可以添加一些验证,例如null检查。如果您实际上改变了DataContext周围环境,我认为也可以致电:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.