代码之家  ›  专栏  ›  技术社区  ›  Sam

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

  •  5
  • Sam  · 技术社区  · 15 年前

    在MVVM应用程序中,我动态地想要显示在运行时可以更改的函数的按钮。从技术上讲,这并不难,在我的视图模型中,我得到了一个可观察到的相关命令集合:

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

    现在在Xaml中,我可以将列表框绑定到此集合:

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

    乍一看,这似乎是工作。
    我的问题是:tabstop命令被破坏了。我希望用户能够从一个按钮跳到另一个按钮,但是列表框不是按钮,而是用户的焦点,我可以使用箭头键而不是制表符在按钮之间进行选择。

    我需要ListBox绑定到集合的能力,但不需要ListBox的任何其他功能。
    我可以用别的面板代替列表框吗?
    或者我可以禁用ListBox函数,让它只显示包含的项,而不能在ListBox中选择它们吗?

    1 回复  |  直到 15 年前
        1
  •  5
  •   lesscode    15 年前

    如果不需要任何列表框功能,请尝试基本项控件而不是列表框:

    <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>
    
    推荐文章