如何在Code中设置绑定?

时间:2011-09-23 06:37:51

标签: c# wpf xaml data-binding

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

我似乎无法做到这一点。

这就是我的尝试:

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

我设置时属性没有更新。

我做错了什么?

3 个答案:

答案 0 :(得分:166)

试试这个:

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

如果您指定path(就像在构造函数中那样),您的来源应该只是ViewModel.SomeString部分会从路径中进行评估。

答案 1 :(得分:10)

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

myBinding.Source = viewModelObject;

答案 2 :(得分: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);
}

我们还遇到过一些情况,就是我们只是将数据上下文保存到本地属性,然后使用它来访问viewmodel属性。选择当然是您的选择,我喜欢这种方法,因为它与其他方法更加一致。您还可以添加一些验证,例如null检查。如果您实际上更改了数据上下文,我认为也可以调用BindingOperations.ClearBinding(myText, TextBlock.TextProperty);来清除旧的视图模型(事件处理程序中的e.oldValue)的绑定会很好。