Search code examples
c#wpfbindinglistboxviewbox

ListView - select index only programmatically


i am trying to implement listbox (or listview):

<ListView ItemsSource="{Binding Players}" SelectedIndex="{Binding SelectedIndex}">

My problem is, that i want to bind selected index to property in code-behind. It work only on form start, but i need to disable user to change selection. Selectin will be changed ONLY programmaticaly.

Thanks for all advices or solutions :)


Solution

  • So, working solution:

    private void playersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (sender.GetType() == typeof(ListView))
        {
            (sender as ListView).SelectedIndex = GameObserver.Instance.core.SelectedIndex;
            e.Handled = true;
        }
    }
    

    In XAML:

    <ListView ItemsSource="{Binding Players}" SelectedIndex="{Binding SelectedIndex}" SelectionChanged="playersList_SelectionChanged">
    

    And bounded property:

    private int selectedIndex = 1;
    public int SelectedIndex
    {
        get
        {
            return selectedIndex;
        }
    }