2016-07-15 97 views
2

我有這個(簡化了SO)列表框:上ListBoxItem的執行按鈕的命令選擇

<ListBox x:Name="CurriculumList" 
      ItemsSource="{Binding FilteredCurriculums}" 
      SelectedIndex="0" 
      SelectionMode="Single" 
      IsSynchronizedWithCurrentItem="True"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Button Name="TheButton" 
        HorizontalContentAlignment="Stretch" 
        Content="{Binding DisplayMember}" 
        CommandParameter="{Binding Id}" 
        Command="{Binding OpenCurriculumEditViewCommand}" /> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

我可以導航上下用鍵盤來改變選擇listBoxItems,但它不會改變的細節查看 - DataTemplate中的Button實際上沒有被點擊,所以OpenCurriculumEditViewCommand從未得到執行。

任何人都有任何想法我可以做到這一點?

回答

0

好吧,如果你想要執行OpenCurriculumEditViewCommandListBox選擇的變化,你可以做到以下幾點:

第一:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 

然後..

<ListBox x:Name="CurriculumList" 
     ItemsSource="{Binding FilteredCurriculums}" 
     SelectedIndex="0" 
     SelectionMode="Single" 
     IsSynchronizedWithCurrentItem="True"> 

    <i:Interaction.Triggers> 
     <i:EventTrigger EventName="SelectionChanged"> 
      <i:InvokeCommandAction CommandParameter="{Binding Path=SelectedItem.Id, RelativeSource={RelativeSource AncestorType=ListBox}}" Command="{Binding OpenCurriculumEditViewCommand}"/> 
     </i:EventTrigger> 
    </i:Interaction.Triggers> 
</ListBox> 
+0

此'ListBox'的'DataContext'綁定到'FilteredCurriculums'屬性,它是ObservableCollection 過濾的'ICollectionView'。 「EventTrigger」如何知道它與「Id」和「OpenCurriculumEditViewCommand」綁定的是哪個「NavigationItemViewModel」? –

+0

我編輯了答案。要綁定到ListBox的SelectedItem的'Id',你可以用它作爲''RelativeSource'到'CommandParameter'的'Binding'。 –

0

如果您希望在選擇時觸發,則根本不應使用Button

+0

我不不一定會有所不同,但可以選擇另一種方法。 「不要這樣做」,雖然技術上正確,但並不真正幫助。 –

+0

只需綁定「SelectedItem」並在綁定屬性的setter中執行命令的邏輯即可。還有幾種替代方案,它並不是很複雜。 –