使用itemtemplate获取ListBox中的SelectedItem仅包含一个按钮

使用itemtemplate获取ListBox中的SelectedItem仅包含一个按钮

问题描述:

我一直试图弄清楚这两天了。 我有一个绑定到ObservableCollection的ListBox。 ListBox使用模板来显示集合中每个项目的Button。点击按钮时,我想发出一个命令并传递selectedItem作为参数。使用itemtemplate获取ListBox中的SelectedItem仅包含一个按钮

问题是,当我点击ListBox的SelectedItem按钮为null时,listBox从不会获得焦点来更改其选择。从我在SO中发现的按钮单击事件中断ListBox SelectionChanged。 这是我的XAML列表框,我的视图模型使用Prism 6.3 DelegateCommand来发布一个事件。

<ListBox Name="PatientsListBox" 
     ItemsSource="{Binding Patients}" 
     SelectedItem="{Binding SelectedPatient}" 
     HorizontalContentAlignment="Stretch" 
     > 

     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <Grid> 
        <Button Content="{Binding Path=Name}" 
          Background="{Binding Path=Sex, Converter={StaticResource ColorConverter}}" 
          Margin="0" Padding="0" 
          Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=ActualWidth, Mode=OneWay}" 
          Command="{Binding ElementName=LayoutRoot, Path=DataContext.ShowPatientCommand}" 
          CommandParameter="{Binding ElementName=PatientsListBox, Path=SelectedItem}"> 
        </Button> 
       </Grid> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
     <ListBox.ItemContainerStyle> 
      <Style TargetType="ListBoxItem"> 
       <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> 
      </Style> 
     </ListBox.ItemContainerStyle> 
    </ListBox> 

是否有可能在没有代码的情况下使用XAML?

我试过使用ItemsControl但它没有SelectedItem属性。 我也尝试使用textBlock模板的交互性,但命令永远不会被解雇。

任何想法?

我终于在MSDN论坛Here is the full thread上找到了答案。我改变了我的CommandParameter结合以下

CommandParameter="{Binding}" 

这指示WPF命令管理器使用DataTemplate中的绑定项。米格尔费尔南德斯科拉尔

就是这样。我希望这将有助于未来的人。 欢呼声