Holger
Holger

Reputation: 73

WPF ListView ignores SelectedItem-change

I am working with a ListView in WPF which is bound an observable collection. I then bound the SelectedItem-Property to a property of the ViewModel.

Furthermore: When I want to "Veto" a SelectedItem Change (because data is not saved), the ListView highlights the new selected item instead of the SelectedItem-Property of the ViewModel.

I already tried to change the Binding to Mode=TwoWay - doesn't work as well (otherwise the "NULL" change to SelectedItem wouldn't work as well)

This is the code from the view:

<ListView ItemsSource="{Binding Configurations}" SelectedItem="{Binding SelectedUserConfiguration}" SelectionMode="Single">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="User Configuration" DisplayMemberBinding="{Binding ConfigurationName}" Width="200" />
        </GridView>
    </ListView.View>
</ListView>

And my ViewModel:

public ObservableCollection<UserConfigurationViewModel> Configurations { get; private set; }
private UserConfigurationViewModel _selectedUserConfiguration;
public UserConfigurationViewModel SelectedUserConfiguration
{
  get { 
    return this._selectedUserConfiguration; 
  }
  set
  {
      if (this._selectedUserConfiguration != null && this._selectedUserConfiguration.WasChanged)
      {
        if (ask-user)
        {
          this._selectedUserConfiguration.Reset();
          this._selectedUserConfiguration = value;
        }
      }
      else
      {
        this._selectedUserConfiguration = value;
      }
      NotifyOfPropertyChange(() => this.SelectedUserConfiguration);
    }
  }

Upvotes: 2

Views: 2756

Answers (2)

trinaldi
trinaldi

Reputation: 2950

I was just having the same issue with a TabControl.

I've tried to create a int property and bind it to SelectedIndex, but no success.

Strangely enough this did the trick:

In your ListView set IsSynchronizedWithCurrentItem="True"

Set a ListView.Resources like this:

<ListView.Resources>
    <Style TargetType="ListViewItem" x:Key="ListViewTemplate">
          <Setter Property="IsSelected" Value="True" />
    </Style>
</ListView.Resources>

Upvotes: 1

Sheridan
Sheridan

Reputation: 69959

In order to select the selected item in any collection control from code, the selected item must be an actual item from the collection that is bound to the ItemsSource property. This can be achieved easily enough with LinQ if your collection items have at least one unique property:

SelectedUserConfiguration = Configurations.Where(c => c.UniqueProperty == 
    valueOfItemToSelect).FirstOrDefault();

If your data type objects do not have a unique property, you can simply add an int Id property for this purpose.

Upvotes: 2

Related Questions