我有一个项目,它设置了用于监视的动态选项卡,因此托管了几个“身份”对象,这些对象是 INotifyPropertyChanged 并且在虚拟应用程序中测试时单独工作。但是,我无法让绑定在我正在处理的应用程序中正常工作。它们已设置,即:
(Configuration.Identities is an ObservableCollection<Identity>)
foreach (Identity id in Configuration.Identities)
{
workTab = new TabItem();
workSettingsTab = new SettingsTabItem();
workTab.DataContext = id;
Binding workTabHeaderBinding = new Binding("Username");
workTabHeaderBinding.Converter = new ToLowerConverter();
workTab.SetBinding(TabItem.HeaderProperty, workTabHeaderBinding);
workSettingsTab.DataContext = id;
Binding workSettingsTabHeaderBinding = new Binding("Username");
workSettingsTabHeaderBinding.Converter = new ToUpperConverter();
workSettingsTab.SetBinding(TabItem.HeaderProperty, workSettingsTabHeaderBinding);
上面的这个东西很好用,大概是因为它是单向的。但是这两个只能单向工作:
workSettingsTab.txtUsername.DataContext = id;
Binding usernameBinding = new Binding("Username");
usernameBinding.Mode = BindingMode.TwoWay;
workSettingsTab.txtUsername.SetBinding(TextBox.TextProperty, usernameBinding);
Binding getJournals = new Binding("LoadJournals");
scrapeJournals.Mode = BindingMode.TwoWay;
workSettingsTab.chkScrapeJournals.DataContext = id;
workSettingsTab.chkScrapeJournals.SetBinding(CheckBox.IsCheckedProperty, scrapeJournals);
我注意到在调试我的保存例程时,上述控件中 DataContext 中引用的 Identity 对象确实包含更改的值,但是我在上面的 foreach 中使用的 ObservableCollection 中的那个没有更新。因此,不知何故,Identity 对象是从最初用于在 foreach 期间设置 DataContext 属性的对象中复制而来的。我在这里做错了什么?