首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在代码中设置绑定?

如何在代码中设置绑定?
EN

Stack Overflow用户
提问于 2011-09-23 14:37:51
回答 4查看 111.6K关注 0票数 106

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

不过,我似乎还是做不好。

这是我尝试过的:

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

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

我做错了什么?

EN

回答 4

Stack Overflow用户

回答已采纳

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

票数 205
EN

Stack Overflow用户

发布于 2011-09-23 14:47:43

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

myBinding.Source = viewModelObject;
票数 12
EN

Stack Overflow用户

发布于 2019-09-04 15:11:32

除了Dypplanswer之外,我认为把它放在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)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7525185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档