2013-02-08 68 views
0

這是我xaml
複選框[內部列表框的ItemTemplate]經過事件不被觸發

<ListBox x:Name="HistoryList"   
        ItemsSource="{Binding HistoryCollection}" 
         > 
     <ListBox.ItemTemplate > 
      </DataTemplate>     
        <CheckBox x:Name="UpCheckBox" Height="50" Width="50" > 
         <interactivity:Interaction.Triggers> 
          <interactivity:EventTrigger EventName="Checked"> 
           <interactivity:InvokeCommandAction Command="{Binding UpCheckedCommad}" CommandParameter="{Binding ElementName=UpCheckBox}"></interactivity:InvokeCommandAction> 
          </interactivity:EventTrigger> 
         </interactivity:Interaction.Triggers> 
        </CheckBox>     
      </DataTemplate> 
     </ListBox.ItemTemplate > 
    </ListBox > 

ViewModel我用GalasoftMVVM Command Binding

public ICommand UpCheckedCommad 
    { 
     get { return new RelayCommand<Object>(x => { PerformUpforTracks(x); }); } 
    } 

    void PerformUpforTracks(object x) 
    { 
     //TODO 
    } 

我用了一個CheckBox裏面ListBox ItemTemplate。但我不在ViewModel中獲得Checked事件CheckBox
我想從ViewModel獲取Checked事件。
任何人都可以有任何想法來解決這個問題?

回答

2

我把它通過用這種方式

Command="{Binding Path=DataContext.UpCheckedCommad, 
      ElementName=HistoryList}" 
2

ListBox.ItemTemplate的每個實例都會自動爲其DataContext指定「集合中的當前項目」。在你的情況下,這是HistoryCollection中的每個單獨項目。在你的例子中,EventTrigger正在當前的HistoryItem實例中搜索「ThumbsUpCheckedCommad」。

爲了強制EventTrigger在您想要的ViewModel中進行搜索,您需要指定命令綁定的「Source」屬性。我建議使用RelativeSource語法來搜索最後一個Control的樹,將ViewModel作爲它的DataContext。

它看起來像這樣。

{Binding Path=ThumbsUpCheckedCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}} 
+0

你能告訴我該命名空間是屬於 'X' 綁定Command? – asitis 2013-02-08 14:01:58

+0

您已經在代碼示例中使用了「x」命名空間。它是XAML模式的內置命名空間。 「AncestorType = {x:Type ListBox}」基本上只是說「向上移動樹直到我們找到一個ListBox,然後在它的DataContext裏面查看我的綁定」。 – BTownTKD 2013-02-08 14:03:35

+0

感謝兄弟的幫助。我得到了答案。無論如何,我沒有從'x'獲得Type。我不知道它爲什麼。 – asitis 2013-02-08 14:07:09

相關問題