在View Model Constructor中设置时,选定的项目不在视图中显示

时间:2014-11-26 03:05:15

标签: c# wpf mvvm data-binding

在我的WPF MVVM应用程序中,我试图在视图首次加载时显示所选项目。在视图模型的构造函数中设置所选项时,这些项在视图中不显示为已选中。但是,在用户单击按钮后执行相同的代码时,项目将显示为已选中。

我的观点,绑定到SelectedCustomVariableGroups

<ListBox DockPanel.Dock="Bottom" ItemsSource="{Binding CustomVariableGroups}" DisplayMemberPath="Name"                     
    ff:MultiSelectorBehaviours.SynchronizedSelectedItems="{Binding SelectedCustomVariableGroups}"
    SelectionMode="Extended" Height="auto">
</ListBox>

我的视图模型的构造函数,设置所选项目:

public CustomVariableGroupSelectorViewModel()
{
    Initialize();

    var selectedCvg = this.CustomVariableGroups.FirstOrDefault(x => x.Name == "Unit RAF44");
    this.SelectedCustomVariableGroups.Add(selectedCvg);  // SelectedCustomVariableGroups is an ObservableCollection
}

SelectedCustomVariableGroups的观察窗口显示计数为1,但在视图中未选择所选项目。

现在,在Cancel()方法中使用相同的代码,就像测试一样(用户通过单击启动它):

private void Cancel()
{
    var selectedCvg = this.CustomVariableGroups.FirstOrDefault(x => x.Name == "Unit RAF44");
    this.SelectedCustomVariableGroups.Add(selectedCvg);
}

当我在这个方法的第一个大括号上调试中断时,this.SelectedCustomVariableGroups.Count从1变为0.为什么?我没有看到任何导致这种情况发生的地方。在Cancel()方法完成后,计数再次返回到1,现在所选项目在视图中正确显示。

为什么这不起作用?如果我无法在构造函数中设置所选项,那么在视图/视图模型加载时如何设置所选项?

1 个答案:

答案 0 :(得分:-2)

尝试设置Mode属性=&#34; TwoWay&#34;使用SelectedItems绑定