【发布时间】:2012-03-22 01:58:48
【问题描述】:
我有一个绑定到可观察集合 (OC) 的 WPF 组合框:
<ComboBox Name="cbCombination" ItemsSource="{Binding Combinations}"
SelectedIndex="0" />
在其他地方,在作为数据上下文的对象集中:
public ObservableCollection<Combination> Combinations { get; set; }
Combination 覆盖了它的 ToString 并且一切都很好:组合框的下拉列表显示了 Combinations OC 中的所有组合项。组合框的选择框显示第一个组合的值。
现在,数据上下文对象必须更改其组合 OC 中的值:
var combinationsList = CombinationsManager.CombinationsFor(someParam);
this.Combinations.Clear();
foreach (var combination in combinationsList)
this.Combinations.Add(combination);
NotifyPropertyChanged(@"Combinations");
这会导致组合框的选择框显示一个空字符串。 (下拉列表已关闭。但是,当我将其下拉时,它确实显示了正确的新组合,因此它绑定到更新的集合。
我试图捕获 SourceUpdated 和(令我失望的)TargetUpdated 事件(想在那里设置 SelectedIndex),但我的事件处理程序没有被调用!
所以我的问题是:当 WPF ComboBox 绑定到的可观察集合发生变化时,如何让 WPF ComboBox 刷新其选择框的值?
更新:
我完全忘了提及,我不知道它是否重要,但组合框位于 UserControl 中。 UserControl 的 XAML 如下所示:
<UserControl x:Class="...CombinationsToolBar"
.... mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<ToolBarTray Name="toolBarTray1" >
<ToolBar Name="toolBar1">
<ComboBox Name="cbCombination"
ItemsSource="{Binding Path=Combinations, NotifyOnSourceUpdated=True,
IsAsync=True}"
SelectedIndex="0" IsEditable="False"
SelectionChanged="CbCombinationSelectionChanged"
SourceUpdated="CbCombinationSourceUpdated"
TargetUpdated="CbCombinationTargetUpdated"></ComboBox>
</ToolBar>
</ToolBarTray>
在 UserControl 的代码中我在 CbCombinationSelectionChanged、CbCombinationSourceUpdated 和 CbCombinationTargetUpdated 上有断点。
CbCombinationSelectionChanged 在首次加载包含用户控件的表单时触发一次。正如@asktomsk 所说,在清除组合集合时确实会第二次调用它。
不触发更新的源和更新的目标 - 不调用 CbCombinationSourceUpdated 和 CbCombinationTargetUpdated。
由于组合框在用户控件内,而 Combinations 集合在视图模型内,并且视图模型无权访问组合框,我没有机会设置选定的索引组合,除非事件触发。
:(
【问题讨论】:
标签: wpf combobox observablecollection