【发布时间】:2017-10-08 13:40:54
【问题描述】:
这两天我一直在尝试解决这个问题。 我有一个绑定到 ObservableCollection 的 ListBox。 ListBox 使用模板为集合中的每个项目显示一个 Button。我想在单击按钮时触发命令并将 selectedItem 作为参数传递。
问题是当我单击按钮时,列表框的 SelectedItem 为空,列表框永远不会获得焦点来更改其选择。从我在 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 模板的交互性,但该命令从未触发。
有什么想法吗?
【问题讨论】: