简体   繁体   English

WPF MVVM:用于将ICommands列表绑定到ListBox的ItemTemplate

[英]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. 在MVVM应用程序中,我动态地希望显示可在运行时更改的功能按钮。 Technically this ain't so difficult, in my ViewModel I've got an observablecollection of RelayCommands: 从技术上讲,这并不是那么困难,在我的ViewModel中,我有一个可观察到的RelayCommands集合:

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

Now in Xaml I can bind a ListBox to this Collection: 现在,在Xaml中,我可以将ListBox绑定到此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. 我希望用户能够从一个按钮跳到另一个按钮,但是ListBox代替了按钮,而是吸引了用户的注意力,我可以使用箭头键而不是Tab键在按钮之间进行选择。

I need the ListBox ability to bind to a collection, but I do not need any other of the listbox functionality. 我需要具有绑定到集合的ListBox功能,但不需要任何其他listbox功能。
Is there some other panel instead of ListBox I can use? 是否可以使用ListBox以外的其他面板?
Or can I somehow disable the ListBox functions so it just shows the contained items without being able to select them in the ListBox? 还是我可以以某种方式禁用ListBox函数,使其仅显示所包含的项目而无法在ListBox中选择它们?

Try a base ItemsControl instead of a ListBox if you don't need any of the ListBox functionality: 如果不需要任何ListBox功能,请尝试使用基本ItemsControl而不是ListBox:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM