我一直試圖弄清楚這兩天了。 我有一個綁定到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模板的交互性,但命令永遠不會被解僱。
任何想法?