0
votes

In my WPF MVVM app, I'm trying to display selected items when a view first loads. When setting the selected items in the constructor of the view model, the items aren't showing as selected in the view. However, when executing that same code after the user clicks a button, the items then show as selected.

My view, with the binding to SelectedCustomVariableGroups.

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

The constructor of my view model, setting the selected items:

public CustomVariableGroupSelectorViewModel()
{
    Initialize();

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

The watch window for SelectedCustomVariableGroups shows a count of 1, however the selected item isn't selected in the view.

Now, the same code in the Cancel() method, just as a test (user initiates this with a click):

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

When I debug-break on the first curly brace in this method, this.SelectedCustomVariableGroups.Count changes from 1 to 0. Why? I don't see anywhere that I'm causing that to happen. After the Cancel() method completes, the count is back to 1 again and now the selected item shows properly in the view.

Why isn't this working? And if I can't set the selected item in the constructor, how can I set the selected items when the view/view model loads?

1
Can you try forcing a PropertyChanged event by passing the SelectedCustomVariableGroups - DevEstacion
I've tried that but it doesn't help. SelectedCustomVariableGroups has a count of 1 and the getter is getting hit repeatedly. - Bob Horn
Check this article though I'm not sure if it'd be helpful, you have the same scenario though he didn't have any problems, blog.functionalfun.net/2009/02/… - DevEstacion
Better to show some code from MultiSelectorBehaviors class. - Jawahar
Do you have this problem also when you execute your code in the loaded event of the view? - user3596113

1 Answers

-2
votes

Try setting the Mode property = "TwoWay" with your SelectedItems binding