【问题标题】:WPF MVVM: ItemTemplate for binding a list of ICommands to a ListBoxWPF MVVM:用于将 ICommand 列表绑定到 ListBox 的 ItemTemplate
【发布时间】:2011-05-09 01:08:12
【问题描述】:

在 MVVM 应用程序中,我动态地希望显示可在运行时更改的功能按钮。从技术上讲,这并不难,在我的 ViewModel 中,我有一个可观察的 RelayCommands 集合:

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

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

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

乍一看,这似乎是有效的。
我的问题是:制表位顺序已损坏。我希望用户能够从一个按钮跳到另一个按钮,但是 ListBox 不是按钮,而是让用户获得焦点,我可以使用箭头键而不是制表符在按钮之间进行选择。

我需要 ListBox 绑定到集合的能力,但我不需要任何其他列表框功能。
我可以使用其他面板而不是 ListBox 吗?
或者我可以以某种方式禁用 ListBox 功能,以便它只显示包含的项目而无法在 ListBox 中选择它们?

【问题讨论】:

    标签: c# wpf mvvm binding listbox


    【解决方案1】:

    如果您不需要任何 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>
    

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 2013-02-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 2014-08-02
      相关资源
      最近更新 更多