Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM: ItemTemplate for binding a list of ICommands to a ListBox

In a MVVM app I dynamically want to show buttons for functions which can be changed during runtime. Technically this ain't so difficult, in my ViewModel I've got an observablecollection of RelayCommands:

public ObservableCollection<RelayCommand> CustomCommands {get;set;}

Now in Xaml I can bind a ListBox to this Collection:

<StackPanel Orientation="Horizontal">
  <ListBox ItemsSource="{Binding CustomCommands}">
    <ListBox.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"/>
      </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
      <DataTemplate>
        <wpfhlp:RelayButton DataContext="{Binding}"/>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>
</StackPanel>

At first glance this looks like it is working.
My problem is: the tabstop order is broken. I want the user to be able to jump from button to button, but instead of the button the ListBox gets the users focus, and I can select between buttons using the arrow keys instead of tab.

I need the ListBox ability to bind to a collection, but I do not need any other of the listbox functionality.
Is there some other panel instead of ListBox I can use?
Or can I somehow disable the ListBox functions so it just shows the contained items without being able to select them in the ListBox?

like image 658
Sam Avatar asked Nov 12 '10 12:11

Sam


1 Answers

Try a base ItemsControl instead of a ListBox if you don't need any of the ListBox functionality:

<StackPanel Orientation="Horizontal">
  <ItemsControl ItemsSource="{Binding CustomCommands}">
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"/>
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <wpfhlp:RelayButton DataContext="{Binding}"/>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</StackPanel>
like image 138
lesscode Avatar answered Sep 28 '22 06:09

lesscode