2013-04-10 69 views
2

我有一個使用MVVM的WPF應用程序。如何將命令添加到ListBox.ItemTemplate

此代碼是從我ResourceDictionary.xaml

<DataTemplate x:Key="LogListTemplate"> 
     <ListBox ItemsSource="{Binding LogList, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource HorizontalListBoxItem}"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <Border Style="{StaticResource ErrorBorders}"> 
         <StackPanel ToolTip="{Binding Details}" Width="250"> 
          <TextBlock Text="{Binding Title}" /> 
          <TextBlock Text="{Binding Details}" TextWrapping="Wrap" /> 
          <Button Command="{Binding AddToTempDtdFileCommand}" CommandParameter="{Binding Details}" Content="Ignore" /> 
         </StackPanel> 
        </Border> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 
    </DataTemplate> 

當我點擊按鈕,該命令不執行。測試證實這是因爲我的Button位於ListBox中。

我的問題是我無法將按鈕移出列表框出於兩個原因。

1. Asthetics/UI (the button has belong with the information) 
2. Binding to the LogList is done from within the ListBox.ItemTemplate 

有沒有人有什麼建議?

回答

2

如果該命令在ViewModel中定義,則可以使用RelativeSource來達到該命令。 RelativeSource可以找到一個祖先(這是你的View),所以你可以使用它的DataContext(你的ViewModel)。

<Button Command="{Binding DataContext.AddToTempDtdFileCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourViewClass}}}" CommandParameter="{Binding Details}" Content="Ignore" /> 
相關問題